i don't know where to start. i have a dropdown list and onchange it will pass 2 values. from it i need to append form set base on setting (select query from database from the value i pass)
index.php
<div class="form-group">
<label for="add-name" class="col-sm-4 control-label">Staff</label>
<div class="col-sm-8">
<?php
$sqlEmpSelect = "select * from payroll_emp order by emp_name";
$qryEmpSelect = sqlsrv_query( $conn, $sqlEmpSelect );
?>
<select name="dpEmp" id="dpEmp" class="form-control">
<option>Sila Pilih</option>
<?php while( $rowAllow = sqlsrv_fetch_array( $qryEmpSelect, SQLSRV_FETCH_ASSOC) ) { ?>
<option value="<?=$rowAllow['emp_id']?>"><?=$rowAllow['emp_name']?></option>
<?php
}
sqlsrv_free_stmt($qryEmpSelect);
?>
</select>
</div>
</div>
<div class="form-group">
<label for="add-template" class="col-sm-4 control-label">Template</label>
<div class="col-sm-8">
<select name="dpTemp" id="dpTemp" class="form-control">
<option value="">Sila Pilih</option>
<?php
$sqlTemp = sprintf("select * from payroll_template order by template_name");
$qryTemp = mysql_query($sqlTemp) or die(mysql_error());
while ($resTemp = mysql_fetch_assoc($qryTemp)) {
?>
<option value="<?php echo $resTemp['template_id']; ?>"/><?php echo $resTemp['template_name']; ?></option>
<?php } ?>
</select>
</div>
</div>
<div id="div-data" name="div-data"></div>
here the jquery i try to use it..
$('#div-data').hide();
$('#dpTemp').change(function(){
var empvalue = $('#dpEmp').val();
var tempvalue = $('#dpTemp').val();
if(tempvalue != ""){
$.ajax({
type:'get',
url:'kew8/htmlforms.php',
data:'empid=' + empvalue + '&tempid=' + tempvalue,
success:function(html){
$('#div-data').html(html);
}
});
} else{
$('#div-data').hide();
}
});
here i try to call the forms set..
htmlforms.php
<?php
$sqlselect = "bla bla bla";
$result = "";
if ($result[0]['seeting1'] == 1) {
?>
<div class="form-group">
<label for="add-template" class="col-sm-4 control-label">Template</label>
<div class="col-sm-8">
<select name="dpTemp" id="dpTemp" class="form-control">
<option value="">Sila Pilih</option>
</select>
</div>
</div>
<div class="form-group">
<label for="add-desc" class="col-sm-4 control-label">Keterangan</label>
<div class="col-sm-8">
<textarea id="txtDesc" name="txtDesc" class="form-control"></textarea>
</div>
</div>
<?php
}
if ($result[0]['seeting2'] == 2) {
?>
<div class="form-group">
<label for="add-template" class="col-sm-4 control-label">Template</label>
<div class="col-sm-8">
<select name="dpTemp" id="dpTemp" class="form-control">
<option value="">Sila Pilih</option>
</select>
</div>
</div>
<div class="form-group">
<label for="add-desc" class="col-sm-4 control-label">Keterangan</label>
<div class="col-sm-8">
<textarea id="txtDesc" name="txtDesc" class="form-control"></textarea>
</div>
</div>
<?php } ?>
and more setting
Related
I input data with dynamics form, where one column contains multiple data using implode (,). but when I input, the dynamic form manages to do as many inputs as I want, but for "mekanik" table it becomes one.
pict one : modal for input data
for "keluhan" has been filled each table is different, but "mekanik" become one value. how to separate it?
in the mechanical column, the first row should be the operator and the second row should be abdullah muis.
pict two : table
here's my code:
this is my input "keluhan" and "mekanik" modal code, i use dynamic_fuild for dynamic form.
enter image description here
<?php
// mengambil data barang dari tabel dengan kode terbesar
$query = mysqli_query($connect, "SELECT max(kode_pg) as kodeTerbesar FROM tb_pg_cs");
$data = mysqli_fetch_array($query);
$kodepg = $data['kodeTerbesar'];
// mengambil angka dari kode barang terbesar, menggunakan fungsi substr dan diubah ke integer dengan (int)
$urutan = (int) substr($kodepg, 2, 7);
// nomor yang diambil akan ditambah 1 untuk menentukan nomor urut berikutnya
$urutan++;
// membuat kode barang baru
// string sprintf("%03s", $urutan); berfungsi untuk membuat string menjadi 3 karakter
// misalnya string sprintf("%03s", 22); maka akan menghasilkan '022'
// angka yang diambil tadi digabungkan dengan kode huruf yang kita inginkan, misalnya PC
$huruf = "SC";
$kodepg1 = $huruf . sprintf("%07s", $urutan);
?>
<?php
include "support/fungsi_romawi.php";
$bulan = date('n');
$romawi = getRomawi($bulan);
// mengambil data barang dari tabel dengan kode terbesar
$query = mysqli_query($connect, "SELECT max(kode_pg) as kodeTerbesar FROM tb_pg_cs");
$data = mysqli_fetch_array($query);
$kodepg = $data['kodeTerbesar'];
// mengambil angka dari kode barang terbesar, menggunakan fungsi substr dan diubah ke integer dengan (int)
$urutan = (int) substr($kodepg, 6, 6);
// nomor yang diambil akan ditambah 1 untuk menentukan nomor urut berikutnya
$urutan++;
// membuat kode barang baru
// string sprintf("%03s", $urutan); berfungsi untuk membuat string menjadi 3 karakter
// misalnya string sprintf("%03s", 22); maka akan menghasilkan '022'
// angka yang diambil tadi digabungkan dengan kode huruf yang kita inginkan, misalnya PC
$tahun = date ('Y');
$nomor = "FORM/SC/".$romawi."/".$tahun."/";
$kode = sprintf("%07s", $urutan);
$noformpg = $nomor. $kode;
?>
<div class="modal fade" id="addnew" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<center><h4 class="modal-title" id="myModalLabel">Tambah Data</h4></center>
</div>
<div class="modal-body">
<div class="container-fluid">
<form method="POST" action="system/add_pg.php" id="form_materi">
<input class="form-control" type="hidden" name="kodepg" value="<?php echo $kodepg1 ?>" required>
<div class="row form-group">
<div class="col-sm-3">
<label class="control-label modal-label">NO. PENGAJUAN</label>
</div>
<div class="col-sm-9">
<input class="form-control" type="text" name="noformpg" value="<?php echo $noformpg ?>" required>
</div>
</div>
<div class="row form-group">
<div class="col-sm-3">
<label class="control-label modal-label">TANGGAL</label>
</div>
<div class="col-sm-9">
<input class="form-control" type="date" name="waktupg" placeholder="Masukkan Hari dan Tanggal Pengajuan" autocomplete="off" required>
</div>
</div>
<div class="row form-group">
<div class="col-sm-3">
<label class="control-label modal-label">DEPARTEMEN</label>
</div>
<div class="col-sm-9">
<select class="form-control selectpicker" type="text" name="deptpg" id="deptpg" data-live-search="true" required>
<option selected value> -- Pilih Departemen -- </option>
<?php
$query = mysqli_query($connect, "SELECT nama_dept FROM tb_dept");
while ($data = mysqli_fetch_array($query)) {
?>
<option value="<?=$data['nama_dept'];?>"><?php echo $data['nama_dept'];?></option>
<?php
}
?>
</select>
</div>
</div>
<div class="row form-group">
<div class="col-sm-3">
<label class="control-label modal-label">LOKASI</label>
</div>
<div class="col-sm-9">
<select class="form-control selectpicker" type="text" name="lokasipg" id="lokasipg" data-live-search="true" required>
<option selected value> -- Pilih Lokasi -- </option>
<option value="JLA 1">JLA 1</option>
<option value="JLA 2">JLA 2</option>
</select>
</div>
</div>
<div class="row form-group">
<div class="col-sm-3">
<label class="control-label modal-label">NAMA MESIN</label>
</div>
<div class="col-sm-9">
<select class="form-control selectpicker" type="text" name="merkpg" id="merkmes" onchange="auto_complete()" data-live-search="true" required>
<option selected value> -- Pilih Mesin -- </option>
<optgroup label="Mesin Forklift">
<?php
$query = mysqli_query($connect, "SELECT * FROM tb_mesin_forklift");
while ($data = mysqli_fetch_array($query)) {
?>
<label><label>
<option value="<?=$data['merk_mesin'];?>"><?php echo $data['merk_mesin'];?> (<?php echo $data['tahun_mesin'];?>)</option>
<?php
}
?>
</optgroup>
<optgroup label="Mesin Produksi">
<?php
$query = mysqli_query($connect, "SELECT * FROM tb_mesin_produksi");
while ($data = mysqli_fetch_array($query)) {
?>
<label><label>
<option value="<?=$data['nama_mesin'];?>"><?php echo $data['nama_mesin'];?> (<?php echo $data['tahun_mesin'];?>)</option>
<?php
}
?>
</optgroup>
</select>
</div>
</div>
<div class="row form-group">
<div class="col-sm-3">
<label class="control-label modal-label">TAHUN</label>
</div>
<div class="col-sm-9">
<input class="form-control" type="text" id="tahunmes" name="tahunpg" placeholder="Masukkan Tahun Mesin" required autocomplete="off">
</div>
</div>
<div class="row form-group">
<div class="col-sm-3">
<label class="control-label modal-label">OPERATOR</label>
</div>
<div class="col-sm-9">
<select class="form-control selectpicker" type="text" name="oppg[]" id="oppg" multiple data-live-search="true" data-none-selected-text="Pilih Operator">
<?php
$query = mysqli_query($connect, "SELECT nama_op FROM tb_operator");
while ($data = mysqli_fetch_array($query)) {
?>
<option value="<?=$data['nama_op'];?>"><?php echo $data['nama_op'];?></option>
<?php
}
?>
</select>
</div>
</div>
<div id="dynamic_field">
<div class="row form-group">
<div class="col-sm-3">
<label class="control-label modal-label">KELUHAN</label>
</div>
<div class="col-sm-7">
<textarea class="form-control" type="text" name="keluhanpg[]" placeholder="Masukkan Keluhan" autocomplete="off" rows="3"></textarea>
</div>
</div>
<div class="row form-group">
<div class="col-sm-3">
<label class="control-label modal-label">MEKANIK</label>
</div>
<div class="col-sm-7">
<select class="form-control selectpicker" type="text" name="mkpg[]" id="mkpg" multiple data-live-search="true" data-none-selected-text="Pilih Mekanik">
<?php
$query = mysqli_query($connect, "SELECT nama_mk FROM tb_mekanik");
while ($data = mysqli_fetch_array($query)) {
?>
<option value="<?=$data['nama_mk'];?>"><?php echo $data['nama_mk'];?></option>
<?php
}
?>
</select>
</div>
<div class="col-sm-2">
<button class="btn btn-success" type="button" name="add" id="add">
<i class="glyphicon glyphicon-plus"></i>
</button>
</div>
</div>
</div>
<div class="row form-group">
<div class="col-sm-3">
<label class="control-label modal-label">SHIFT</label>
</div>
<div class="col-sm-9">
<select class="form-control selectpicker" type="text" name="shiftpg" id="shiftpg" data-live-search="true">
<option selected value> -- Pilih Shift -- </option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>
</div>
<input type="hidden" class="form-control" name="statuspg" value="PROGRESS">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal"><span class="glyphicon glyphicon-remove"></span> Cancel</button>
<button type="submit" name="add" class="btn btn-primary"><span class="glyphicon glyphicon-floppy-disk"></span> Save</a>
</div>
</form>
</div>
</div>
</div>
</div>
I use javascript to be able to add input fields because they are dynamics.
$(document).ready(function(){
var i=1;
$('#add').click(function(){
i++;
$('#dynamic_field').append('<div id="row'+i+'"><div class="row form-group"><div class="col-sm-3"><label class="control-label modal-label">KELUHAN</label></div><div class="col-sm-7"><textarea class="form-control" type="text" name="keluhanpg[]" placeholder="Masukkan Keluhan" autocomplete="off" rows="3" required></textarea></div></div><div class="row form-group"><div class="col-sm-3"><label class="control-label modal-label">MEKANIK</label></div><div class="col-sm-7"><select class="form-control selectpicker" type="text" name="mkpg[]" id="mkpg" multiple data-live-search="true" data-none-selected-text="Pilih Mekanik" required> <?php $query = mysqli_query($connect, "SELECT nama_mk FROM tb_mekanik"); while ($data = mysqli_fetch_array($query)) { ?> <option value="<?=$data['nama_mk'];?>"><?php echo $data['nama_mk'];?></option> <?php } ?></select></div><div class="col-sm-2"><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove"><i class="fa fa fa-trash"></i></button></div></div></div>');
$(".selectpicker").selectpicker('refresh');
});
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
// alert(button_id);
$('#row'+button_id+'').remove();
});
});
and this is the code for my input process.
<?php
session_start();
include_once('koneksi.php');
if(isset($_POST['add'])){
$kodepg = $_POST['kodepg'];
$noformpg = $_POST['noformpg'];
$waktupg = $_POST['waktupg'];
$deptpg = $_POST['deptpg'];
$lokasipg = $_POST['lokasipg'];
$merkpg = $_POST['merkpg'];
$tahunpg = $_POST['tahunpg'];
$op = isset($_POST['oppg']) && is_array($_POST['oppg']) ? $_POST['oppg'] : [];
$oppg = implode(", ", $op);
$keluhanpg = isset($_POST['keluhanpg']) && is_array($_POST['keluhanpg']) ? $_POST['keluhanpg'] : [];
$mk = isset($_POST['mkpg']) && is_array($_POST['mkpg']) ? $_POST['mkpg'] : [];
$mkpg = implode(", ", $mk);
$shiftpg = $_POST['shiftpg'];
$statuspg = $_POST['statuspg'];
foreach ($_POST['keluhanpg'] as $key => $value) {
$sql = "INSERT INTO tb_pg_cs (kode_pg,noform_pg,waktu_pg,dept_pg,lokasi_pg,merk_pg,tahun_pg,op_pg,keluhan_pg,mk_pg,shift_pg,status_pg) VALUES ('" . $kodepg . "','".$noformpg . "','".$waktupg . "','".$deptpg . "','".$lokasipg . "','".$merkpg . "','".$tahunpg . "','".$oppg . "','".$_POST['keluhanpg'][$key] . "','".$mkpg. "','".$shiftpg . "','".$statuspg . "')";
//use for MySQLi OOP
if($connect->query($sql)){
$_SESSION['success'] = 'Data added successfully';
}
else{
$_SESSION['error'] = 'Something went wrong while adding';
}
}
}
header("location: ".$base_url."index.php?page=pengajuan");
?>
In codeigniter I want to add the product on admin Id which is required in DB Table. when Admin log in his ID must be catch. whenever and where Id is needed it must be available.
here is my VIEW in which
<?php echo form_open_multipart('admin/add_product');?>
<!------------------Product Name------------------------>
<div class="row form-group">
<div class="col-sm-10">
<label>Product Name: *</label>
<?php echo form_input(['name'=>'name','class'=>'form-
control','placeholder'=>'Product name..','value'=>
set_value('name')])?>
<div>
<?php echo form_error('name');?>
</div>
</div></div>
<!------------------Product Cat---------------------------->
<div class="row form-group">
<div class="col-sm-12">
<label>Category: *</label> <br>
<select class="selectpicker" name="pro_cat_id">
<option label="Select Category">Category</option>
<?php
foreach($product_cat as $cat)
{?>
<option value="<?= $cat['pro_cat_id'] ?>"><?= $cat['category'] ?>
</option>
<?php }?>
</select>
<div>
<!------------------Product Price---------------------------->
<div class="row form-group">
<div class="col-md-10">
<label>Product Price: *</label>
<?php echo form_input(['name'=>'price','class'=>'form-
control','placeholder'=>'Product Price..','value'=>
set_value('price')])?>
<div>
<?php echo form_error('price');?>
</div>
</div></div>
<!------------------Product Location---------------------------->
<div class="row form-group">
<div class="col-md-10">
<label>Product Location: *</label>
<?php //echo form_input(['name'=>'location','class'=>'form-
control','placeholder'=>'Product Location'])?>
</div></div>
</div></div>
<!-----------End of body---------------->
</div>
<div class="modal-footer">
<input name="" type="submit" value="ADD" class="btn btn-success">
</div>
<?php echo form_close();?>
</div>
</div>
</div>
Here is my Controller
function add_product(){
$data['product_size'] = $this->show->show_product_size();
$data['product_cat']= $this->show->show_product_category();
$data['product_color'] = $this->show->show_product_color();
$data['pr']= $this->show->show_provider();
$post= $this->input->post();
$ =this->form_validation->set_error_delimiters("<p class='text-danger'>","
</p>");
if($this->form_validation->run('add_product')){
if($this->add->add_product($post)==TRUE){
$this->db->close();
$this->session->set_flashdata('success','Product has been added
successfully');
return redirect('admins/pages/add_product_page');
//$this->load->admin_template('admin/add_product',$data);
}
}
else
{
$this->session->set_flashdata('failled','Sorry, fail to add product');
//return redirect('admins/pages/add_product_page');
$upload_error= $this->upload->display_errors();
$this->load->admin_template('admin/add_product',$data);
}
}
Use this query, preferably in your controller:
$this->session->userdata('id');
If i select Local Sales from dorpdown and enter DEF, GHI values then the sum of DEF,GHI should be displayed in total value or if i select Inter State,Stock Transfers from dropdown then if we enter ABC value that value should be displayed in total value or else if we select JOB WORK,EXEMPTED SALES from dropdown then the total value should be displayed as zero. The total value which ever we are getting that should be inserted into database.
Controller:
function addinvoice()
{
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<br /><span class="error"> ','</span>');
$this->form_validation->set_rules('user','User');
$this->form_validation->set_rules('freight_charges');
$this->form_validation->set_rules('abc');
$this->form_validation->set_rules('def');
$this->form_validation->set_rules('ghi');
$this->form_validation->set_rules('total');
if($this->form_validation->run()== FALSE)
{
$data['mainpage']='invoice';
$data['mode']='add';
$this->load->view('templates/template',$data);
}
else
{
$this -> invoice_model -> insert();
$this->flash->success('<h2> Details added Successfully!</h2>');
redirect('invoice');
}
}
Model:
function insert()
{
$data['total']=0;
$data['user'] = $this->input->post('user');
$data['ghi'] = ($this->input->post('ghi'))?$this->input->post('ghi'):0;
$data['abc'] = ($this->input->post('abc'))?$this->input->post('abc'):0;
$data['def'] = ($this->input->post('def'))?$this->input->post('def'):0;
$data['total'] = $data['ghi'] + $data['abc'] + $data['def'];
$data['freight_charges'] = $this->input->post('freight_charges');
$this->db->insert('invoice',$data);
}
View:
<script>
function showRequiredOption(cval)
{
if((cval=='interstate') || (cval == "stocktransfers"))
{
$('#ghi').hide();
$('#def').hide();
$('#abc').show();
}
else if ((cval=='exemptedsales') || (cval=="zeroratedsales") ||(cval=="jobwork"))
{
$('#ghi').hide();
$('#def').hide();
$('#abc').hide();
}
else
{
$('#abc').hide();
$('#ghi').show();
$('#def').show();
}
}
</script>
<div class="col-md-9 col-md-offset-2">
<div id="legend">
<legend class="">Profile Information</legend>
</div>
<form role="form" action="<?php echo site_url();?>invoice/addinvoice" method="post" class="form-horizontal" id="location" method="post" accept-charset="utf-8">
<div class="form-group">
<label class="control-label col-sm-2 " for="user">User</label>
<div class="col-sm-4 col-sm-offset-1">
<select id="user" name="user" onchange="showRequiredOption(this.value)">
<option value="employee">Local Sales</option>
<option value="interstate">Inter state</option>
<option value="stocktransfers">Stock transfers</option>
<option value="exemptedsales">Exempted Sales</option>
<option value="zeroratedcompany">Zero Rated Sales</option>
<option value="jobwork">Job Work</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2 " for="freight_charges">Freight Charges</label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control" id="freight_charges" name="freight_charges" value="<?php echo set_value('freight_charges');?>" />
</div>
</div>
<div class="form-group" id="abc" style="display:none;">
<label class="control-label col-sm-2 " for="abc">ABC</label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control" id="abc" name="abc" value="<?php echo set_value('abc');?>"/ >
</div>
</div>
<div class="form-group" id="def">
<label class="control-label col-sm-2 " for="def">DEF </label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control" id="def" name="def" value="<?php echo set_value('def');?>"/ >
</div>
</div>
<div class="form-group" id="ghi">
<label class="control-label col-sm-2 " for="ghi">GHI</label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control" id="ghi" name="ghi" value="<?php echo set_value('ghi');?>"/ >
</div>
</div>
<div class="form-group" id="cgst">
<label class="control-label col-sm-2 " for="total">Total</label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control" name="total" >
</div>
</div>
<button id="submit" type="submit" class="btn" name="submit">Submit</button>
</form>
</div>
Whatever values i have selected from dropdown only those values to be inserted into database and the rest of the values should be inserted as zero in the database.
Actually i am not getting how to do these can anyone check this.Thanks in Advance.
you should check for posted values in your php code as:
$total = 0;
if($this->input->post('this')){
$total = $this->input->post('this');//value in total
}
if($this->input->post('this2')){
$total += $this->input->post('this2');//value in total
}
and at the end send $total value in db as well.
in short php if else tags you can set variables like;
$this = ($this->input->post('this'))?$this->input->post('this'):0;
$this2 = ($this->input->post('this2'))?$this->input->post('this2'):0;
and then at the end you can make total of them and save them to database. OR as suggested above in comments that make your columns as DEFAULT 0 in your table.
------- IN YOUR CASE------
function insert()
{
$data['total']=0;
$data['user'] = $this->input->post('user');
$data['ghi'] = ($this->input->post('ghi'))?$this->input->post('ghi'):0;
$data['abc'] = ($this->input->post('abc'))?$this->input->post('abc'):0;
$data['def'] = ($this->input->post('def'))?$this->input->post('def'):0;
$data['total'] = $data['ghi'] + $data['abc'] + $data['def'];
$data['freight_charges'] = $this->input->post('freight_charges');
$this->db->insert('invoice',$data);
}
---------------IN JavaScript------------
on your event handler you can sum these by their IDs.
var total = parseInt($('#ghi').val())+parseInt($('#def').val());
and then show this total in your total div
$('#yourTotalDiv').text(total);
Displaying total amount on enter the details.
<script>
function showRequiredOption(cval)
{
if((cval=='interstate') || (cval == "stocktransfers"))
{
$('#ghi').hide();
$('#def').hide();
$('#abc').show();
}
else if ((cval=='exemptedsales') || (cval=="zeroratedsales") || (cval=="jobwork"))
{
$('#ghi').hide();
$('#def').hide();
$('#abc').hide();
}
else
{
$('#abc').hide();
$('#ghi').show();
$('#def').show();
}
}
</script>
<script>
$(document).ready(function(){
//iterate through each textboxes and add keyup
//handler to trigger sum event
$(".txt").each(function() {
$(this).keyup(function(){
calculateSum();
});
});
});
function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$(".txt").each(function() {
//add only if the value is number
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseFloat(this.value);
}
});
//.toFixed() method will roundoff the final sum to 2 decimal places
$("#sum").html(sum.toFixed(2));
}
</script>
<div class="col-md-9 col-md-offset-2">
<div id="legend">
<legend class="">Profile Information</legend>
</div>
<form role="form" action="<?php echo site_url();?>invoice/addinvoice" method="post" class="form-horizontal" id="location" method="post" accept-charset="utf-8">
<div class="form-group">
<label class="control-label col-sm-2 " for="user">User</label>
<div class="col-sm-4 col-sm-offset-1">
<select id="user" name="user" onchange="showRequiredOption(this.value)">
<option value="employee">Local Sales</option>
<option value="interstate">Inter state</option>
<option value="stocktransfers">Stock transfers</option>
<option value="exemptedsales">Exempted Sales</option>
<option value="zeroratedcompany">Zero Rated Sales</option>
<option value="jobwork">Job Work</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2 " for="freight_charges">Freight Charges</label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control txt" id="freight_charges" name="freight_charges" value="<?php echo set_value('freight_charges');?>" />
</div>
</div>
<div class="form-group" id="abc" style="display:none;">
<label class="control-label col-sm-2 " for="abc">ABC</label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control txt" id="abc" name="abc" value="<?php echo set_value('abc');?>"/ >
</div>
</div>
<div class="form-group" id="def">
<label class="control-label col-sm-2 " for="def">DEF </label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control txt" id="def" name="def" value="<?php echo set_value('def');?>"/ >
</div>
</div>
<div class="form-group" id="ghi">
<label class="control-label col-sm-2 " for="ghi">GHI</label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control txt" id="ghi" name="ghi" value="<?php echo set_value('ghi');?>"/ >
</div>
</div>
<div class="form-group" id="summation">
<label class="control-label col-sm-2 " for="total">Total</label>
<div class="col-sm-4 col-sm-offset-1">
<span id="sum" class="form-control" type="text" name="total">0</span>
</div>
</div>
<button id="submit" type="submit" class="btn" name="submit">Submit</button>
</form>
</div>
I really hope you can help me.
I've done a form, where I can opt if a client I'm adding to the database is "Active or "Inactive", using a dropdown select box.
My code saves all the data correctly to the datbase, but when I want to edit the client, the option displays always as "Active", ignoring the value from the database.
I have 2 files:
edita_clientes.php - the form where I can edit the clients values
salvar_edicao.php - the file that saves the edition.
Here are the codes:
edita_clientes.php:
<?php
#ini_set('display_errors', '1');
error_reporting(E_ALL);
$id = $_GET["id_cliente"];
settype($id, "integer");
mysql_connect("localhost", "root", "");
mysql_select_db("sistema");
$resultado = mysql_query("select * from tabela where id_cliente = $id");
$dados = mysql_fetch_array($resultado);
mysql_close();
?>
<form id="edita_pj" name="edita_pj" method="post" action="salvar_edicao.php">
<input type="hidden" name="id_cliente" id="id_cliente" value="<?php echo $id;?>" />
<div class="box-body">
<div class="form-group">
<label>Razão Social</label>
<input type="text" name="razao" id="razao" class="form-control" value="<?php echo $dados["razao"];?>" />
</div>
<div class="form-group">
<label>Nome Fantasia</label>
<input type="text" name="fantasia" id="fantasia" class="form-control" value="<?php echo $dados["fantasia"];?>" />
</div>
</div>
<div class="box-body">
<div class="form-group">
<label>CNPJ</label>
<input type="text" name="cnpj" id="cnpj" class="form-control" data-inputmask='"mask": "999.999.999-99"' data-mask value="<?php echo $dados["cnpj"];?>">
</div>
</div>
<div class="box-body">
<div class="row">
<div class="col-xs-9">
<label>Logradouro</label>
<input type="text" name="logradouro" id="logradouro" class="form-control" value="<?php echo $dados["logradouro"];?>">
</div>
<div class="col-xs-3">
<label>Número</label>
<input type="text" name="numero" id="numero" class="form-control" value="<?php echo $dados["numero"];?>">
</div>
</div>
</div>
<div class="box-body">
<div class="row">
<div class="col-xs-9">
<label>Bairro</label>
<input type="text" name="bairro" id="bairro" class="form-control" value="<?php echo $dados["bairro"];?>">
</div>
<div class="col-xs-3">
<label>CEP</label>
<input type="text" name="cep" id="cep" class="form-control" data-inputmask='"mask": "99999-999"' data-mask value="<?php echo $dados["cep"];?>">
</div>
</div>
</div>
<div class="box-body">
<div class="row">
<div class="col-xs-10">
<label>Cidade</label>
<input type="text" name="cidade" id="cidade" class="form-control" value="<?php echo $dados["cidade"];?>">
</div>
<div class="col-xs-2">
<label>UF</label>
<input type="text" name="uf" id="uf" class="form-control" value="<?php echo $dados["uf"];?>">
</div>
</div>
</div>
<div class="box-body">
<div class="row">
<div class="col-xs-9">
<label>E-mail</label>
<input type="text" name="email" id="email" class="form-control" value="<?php echo $dados["email"];?>">
</div>
<div class="col-xs-3">
<label>Telefone</label>
<input type="text" name="telefone" id="telefone" class="form-control" data-inputmask='"mask": "(99) 9999.9999"' data-mask value="<?php echo $dados["telefone"];?>"/>
</div>
</div>
</div>
<div class="box-body">
<div class="row">
<div class="col-xs-9">
<label>Contato</label>
<input type="text" name="contato" id="contato" class="form-control" value="<?php echo $dados["contato"];?>">
</div>
<div class="col-xs-3">
<label>Estado</label>
<select class="form-control" name="estado" id="estado" value=""><?php echo $dados["estado"];?>
<option>Ativo</option>
<option>Inativo</option>
</select>
</div>
</div>
<div class="form-group">
<label>Observações</label>
<textarea class="form-control" name="obs" id="obs" rows="6" ><?php echo $dados["obs"];?>
</textarea>
</div>
</div>
<div class="box-footer">
<button type="submit" name="Submit" class="btn btn-primary">Salvar</button>
</div>
</form>
salvar_edicao.php:
<?php
#ini_set('display_errors', '1');
error_reporting(E_ALL);
$razao = $_POST["razao"];
$fantasia = $_POST["fantasia"];
$cnpj = $_POST["cnpj"];
$logradouro = $_POST["logradouro"];
$numero = $_POST["numero"];
$bairro = $_POST["bairro"];
$cep = $_POST["cep"];
$cidade = $_POST["cidade"];
$uf = $_POST["uf"];
$email = $_POST["email"];
$telefone = $_POST["telefone"];
$contato = $_POST["contato"];
$estado = $_POST["estado"];
$obs = $_POST["obs"];
$id = $_POST["id_cliente"];
mysql_connect("localhost", "root", "");
mysql_select_db("sistema");
mysql_query("UPDATE tabela SET razao = '$razao', fantasia = '$fantasia', cnpj = '$cnpj', logradouro = '$logradouro', numero='$numero', bairro='$bairro', cep='$cep', cidade = '$cidade', uf='$uf', email = '$email', telefone = '$telefone', contato = '$contato', estado = '$estado', obs = '$obs' WHERE tabela.id_cliente = $id");
mysql_close();
header("Location: consulta.php");
?>
You need to add 'selected' to the option that you want to be selected, based on a value from the form/db. Here is an example using $value as the option value that you want selected.
<select class="form-control" name="estado" id="estado">
<option <?php echo $value == 'Ativo' ? selected : '' ?>>Ativo</option>
<option <?php echo $value == 'Inativo' ? selected : '' ?>>Inativo</option>
</select>
Also, your <select> tag does not require a 'value' element..
The HTML select element does not have a value attribute. For the select to do what you want you need to add the selected attribute to the option you want selected. It's always showing as 'Active' because that's the first option and it is the default.
The resulting post-php HTML will need to look something like this stripped back example for 'Inactive' to be selected.
<select>
<option>Active</option>
<option selected>Inactive</option>
</select>
Thank's for all the help!
The solution I've found was:
<?php
$resultado = mysql_query("select * from tabela where id_cliente = $id");
$dados = mysql_fetch_array($resultado);
$query = mysql_query("SELECT * FROM estado");
?>
And the html part:
<select class="form-control" name="estado" id="estado">
<option selected="selected"><?php echo $dados["estado"];?></option>
<option value="Ativo">Ativo</option>
<option value="Inativo">Inativo</option>
</select>
I'm currently creating a page where you can fill in damage claims about damaged cars/goods. You have 3 options (driver/subcontractor/personel) and JQuery is used to show/hide different textboxes according to the selected option.
Here's where it gets tricky. Everything works great until I submit the form. When I do it fires the changeVehicle JQuery-function again and reloads the original value in licensePlate again, even after I altered it in the form. The result being that I get the old variable for my license plate.
Does anyone have an idea why it refires?
My code:
<?php
...
<form id="form" class="form-horizontal" method="post" action="<?php echo $url?>&action=edit<?php echo $edit?>" enctype="multipart/form-data">
<div class="control-group">
<label class="control-label" for="filenr"><?php echo $lng->show("claim_file_nr")?></label>
<div class="controls">
<input type="text" id="filenr" name="filenr" value="<?php echo $file_nr?>" disabled>
<input type="hidden" id="file_nr" name="file_nr" value="<?php echo $file_nr?>" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="damage_type"><?php echo $lng->show("claim_damage_type")?>*</label>
<div class="controls">
<select id="damage_type" name="damage_type" <?php if ($par["id"] != 0) { echo "disabled"; } ?>>
<option value="0" <?php if ($damage_type == 0) echo "selected" ?>><?php echo $lng->show("claim_type_vehicle") ?></option>"
<option value="1" <?php if ($damage_type == 1) echo "selected" ?>><?php echo $lng->show("claim_type_goods") ?></option>"
</select>
</div>
</div>
<div class="control-group">
<label class="control-label" for="date_damage"><?php echo $lng->show("claim_date_damage"); ?>*</label>
<div class="controls">
<div class="input-append">
<input class="input-small" type="text" id="date_damage" name="date_damage" data-date-format="dd-mm-yyyy" placeholder="dd-mm-yyyy"
value="<?php echo $cfunc->convertDateFromDB(substr($date_damage, 0, 10)) ?>" required>
<span class="add-on"><i class="icon-calendar"></i></span>
</div>
</div>
</div>
<div class="control-group">
<label class="control-label" for="description"><?php echo $lng->show("claim_description")?>*</label>
<div class="controls">
<textarea class="input-xxlarge" rows="4" id="description" name="description" required><?php echo $description;?></textarea>
</div>
</div>
<div class="control-group">
<label class="control-label" for="choice"><?php echo $lng->show("claim_choice")?>*</label>
<div class="controls controls-row">
<select id="choice" name="choice" onchange="changeChoice();">
<option value="1" <?php if (isset($driver)&& $driver != 0) echo "selected" ?>><?php echo $lng->show("claim_driver") ?></option>"
<option value="2" <?php if (isset($subcontractor)&& $subcontractor != 0) echo "selected" ?>><?php echo $lng->show("claim_subcontractor") ?></option>"
<option value="3" <?php if ($personel != "") echo "selected" ?>><?php echo $lng->show("claim_personel") ?></option>"
</select>
</div>
</div>
<div id="driver-container" class="control-group">
<label class="control-label" for="driver"><?php echo $lng->show("claim_driver")?>*</label>
<div class="controls controls-row">
<select id="driver" name="driver">
<?php
$result = $db->q("SELECT * FROM ERP_drivers");
foreach ($result as $a) {
if ($driver == $a["driver_id"]) {
echo "<option value=".$a["driver_id"]." selected>".$a["driver_name"]."</option>";
}else{
echo "<option value=".$a["driver_id"].">".$a["driver_name"]."</option>";
}
}
?>
</select>
</div>
</div>
<div id="subcontractor-container" class="control-group">
<label class="control-label" for="subcontractor"><?php echo $lng->show("claim_subcontractor")?>*</label>
<div class="controls controls-row">
<select id="subcontractor" name="subcontractor">
<?php
$subcontractors = $db->q("SELECT r.relatie_id, r.relatie_naam
FROM relaties AS r INNER JOIN relatie_lijsten AS l
ON r.relatie_id = l.relatie_lijst_relatie_id
WHERE l.relatie_lijst_relatieslijst_id = 23");
foreach($subcontractors as $s){
if ($subcontractor == $s["relatie_id"]) {
echo "<option value=\"".$s["relatie_id"]."\" selected>".$s["relatie_naam"]."</option>";
}else{
echo "<option value=\"".$s["relatie_id"]."\">".$s["relatie_naam"]."</option>";
}
}
?>
</select>
</div>
</div>
<div id="personel-container" class="control-group">
<label class="control-label" for="personel"><?php echo $lng->show("claim_personel")?>*</label>
<div class="controls controls-row">
<select id="personel" name="personel">
<?php
$personelList = $db->q("SELECT * FROM `erp_gebruiker` WHERE `actief` =1");
foreach($personelList as $p){
if ($personel == $p["gebruiker_id"]) {
echo "<option value=\"".$p["gebruiker_id"]."\" selected>".$p["naam"]."</option>";
}else{
echo "<option value=\"".$p["gebruiker_id"]."\">".$p["naam"]."</option>";
}
}
?>
</select>
</div>
</div>
<div id="vehicle-container" class="control-group">
<label class="control-label" for="vehicle"><?php echo $lng->show("claim_choice_vehicle")?>*</label>
<div class="controls controls-row">
<select id="vehicle" name="vehicle" onchange="changeVehicle();">
<?php
$result = $db->q("SELECT * FROM ERP_vehicles");
foreach ($result as $v) {
if ($vehicle == $v["vehicle_id"]) {
echo "<option value=".$v["vehicle_id"]." selected>".$v["vehicle_name"]."</option>";
}else{
echo "<option value=".$v["vehicle_id"].">".$v["vehicle_name"]."</option>";
}
}
?>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label" for="license_plate"><?php echo $lng->show("claim_license_plate")?></label>
<div class="controls">
<input type="text" id="license_plate" name="license_plate" value="<?php echo $license_plate; ?>">
</div>
</div>
<div class="control-group">
<label class="control-label" for="faulty"><?php echo $lng->show("claim_faulty")?></label>
<div class="controls controls-row">
<select id="faulty" name="faulty">
<option value="0" <?php if ($faulty == 0) echo "selected"; ?>><?php echo $clng->show("no")?></option>";
<option value="1" <?php if ($faulty == 1) echo "selected"; ?>><?php echo $clng->show("yes")?></option>";
</select>
</div>
</div>
<div class="control-group">
<label class="control-label" for="file_insurance"><?php echo $lng->show("claim_insurance_nr")?></label>
<div class="controls">
<input type="text" id="file_insurance" name="file_insurance" value="<?php echo $file_insurance?>">
</div>
</div>
<div class="control-group">
<label class="control-label" for="damage_amount"><?php echo $lng->show("claim_damage_amount")?></label>
<div class="controls">
<input type="number" step="0.01" id="damage_amount" name="damage_amount" value="<?php echo $damage_amount?>">
</div>
</div>
<div class="control-group">
<label class="control-label" for="exemption"><?php echo $lng->show("claim_exemption")?></label>
<div class="controls">
<input type="number" step="0.01" id="exemption" name="exemption" value="<?php echo $exemption?>">
</div>
</div>
<div class="control-group">
<label class="control-label" for="amount_payed"><?php echo $lng->show("claim_amount_payed")?></label>
<div class="controls">
<input type="number" step="0.01" id="amount_payed" name="amount_payed" value="<?php echo $amount_payed?>">
</div>
</div>
<div class="control-group">
<label class="control-label" for="status"><?php echo $lng->show("claim_status")?></label>
<div id="choice" class="controls">
<select id="status" name="status">
<option value="1" <?php if ($status == 1) echo "selected"; ?>><?php echo $lng->show("claim_status_handling")?></option>";
<option value="2" <?php if ($status == 2) echo "selected"; ?>><?php echo $lng->show("claim_status_handled")?></option>";
</select>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary"><?php echo $knop?></button>
<button type="button" class="btn" onclick="javascript:location.href='<?php echo $url?>'"><?php echo $clng->show("cancel")?></button>
</div>
</form>
<script>
$(function () {
$("input,select,textarea").not("[type=submit]").jqBootstrapValidation();
changeChoice();
// alert("blablabla");
});
$("#date_damage").datepicker({format:'dd-mm-yyyy'});
function changeChoice() {
var c = $("#choice :selected").val();
if (c == "1") {
$("#driver-container").show();
$("#subcontractor-container").hide();
$("#personel-container").hide();
} else if (c == "2") {
$("#driver-container").hide();
$("#subcontractor-container").show();
$("#personel-container").hide();
} else {
$("#driver-container").hide();
$("#subcontractor-container").hide();
$("#personel-container").show();
}
changeVehicle()
}
function changeVehicle() {
var choice = $("#choice :selected").val();
var vehiclePlate = $("#vehicle :selected").val();
var licensePlate = '<?php if ($par["id"] == 0 ) { echo ""; } else { echo $license_plate; }?>'
if (choice == "1" || choice == "3") {
$("#vehicle-container").show();
$("#license_plate").prop('disabled', true);
showLicense(vehiclePlate);
$("#license_plate").val(data[0]);
} else {
$("#vehicle-container").hide();
$("#license_plate").prop('disabled', false);
//$("#license_plate").val(licensePlate);
}
}
function showLicense(plate) {
$.ajax({
type: 'POST',
url: 'index.php?page=claims&ajax=getplate',
dataType: 'json',
data: { plate: plate },
success: function(data) {
$("#license_plate").val(data[0]);
}
});
}
</script>
Found it. It seemds that some validation-code is the bad guy. Everything works fine when I put this in comment:
<script>
$(function () {
//$("input,select,textarea").not("[type=submit]").jqBootstrapValidation();
changeChoice();
});
...
</script>
I don't really have an idea why, I'm still pretty new with this JavaScript/JQuery stuff, but at least I can find a workaround for the validation that line provided.