Retrieve data from combobox to other input fields - php

I am PHP beginner and am having problems creating a combobox or a drop down list. The combobox or drop down list contains stock names, when I click any stock, the stock code and producer should be displayed. I have attached the code please. My code works well to retrieve stock code alone. How do I make the stockcode and producer to be retrieved.
This is what I am doing
<label class="col-lg-2 col-form-label" for="val-skill">Select Stock<span class="text-danger">*</span> </label>
<div class="col-lg-6">
<select id="stockname" name="stockname" class="form-control" required="">
<option value="0">Select Stock</option>
<?php
$ddaa = $pdo->query("SELECT id, stockname, stockno, producer FROM storemaster ORDER BY id");
while ($data = $ddaa->fetch(PDO::FETCH_ASSOC))
{
echo "<option value='$data[stockno]', '$data[producer]'> $data[stockname]</option>";
}
?>
</select>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Stock No</label>
<div class="col-sm-6"><input id="stockno" name="stockno" value="" class="form-control" type="text" readonly></div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Producer</label>
<div class="col-sm-6"><input id="producer" name="producer" value="" class="form-control" type="text" ></div>
</div>
<div class="col-sm-6 col-sm-offset-3"><br/><br/><br/>
<input type="submit" class="btn btn-lg btn-success btn-block" value="Submit">
</div>
</form>
</div>
</div>
<script>
document.getElementById("stockname").onchange = function () {
document.getElementById("stockno").value = this.value;
};
</script>

//PHP
echo '<option value="'.$data['stockno'].'" data-producer="'.$data['producer'].'"> '.$data['stockname'].'</option>';
<!--HTML Javascript-->
<script>
$('#stockname').on('change',function(){
if($(this).val() !=0){
$('#stockno').val($(this).val());
$('#producer').val($(this).attr('data-producer'));
}
});
</script>

Related

Laravel 9: Data does not appear before editing when the ID is changed then the form autofills using JQUERY AJAX

good afternoon everyone. I'm making a form to edit leave allocation data with jquery ajax. the form consists of (id_kategoricuti, id_karyawan,durasi, mode_alokasi, tgl_masuk, tgl_sekarang, aktif_dari, sampai).
Previously in from create, the conditions are:
when id_kategoricuti is selected, the form durasi, mode_alokasi will be filled in automatically using ajax.
For example, in the selected id_kategoricuti id form Cuti Tahunan, the tgl_masuk and tgl_sekarang forms will appear.
then, when selecting id_karyawan, the tanggal_masuk form will automatically be filled according to the entry date data in the employee table. so that only the aktif_dari and sampai forms are filled in.
condition from edit leave allocation:
data appears according to the id that has been selected.
the user makes changes to the desired data.
save.
however, I'm facing a problem on this edit form:
because when I click on one of the data to edit, what appears on the form is only id_kategoricuti and id_karyawan.
the form mode_alokasi, durasi, aktif_dari and sampai are empty.
The form was only filled in when id_karyawan/id_kagotericuti was edited.
the data in the box below the category form is the data that should appear on the form.
This is the appearance of the leave allocation edit form before editing:
this is the appearance of the leave allocation edit form after the leave id_categories are edited:
my Controller:
public function getTglmasuk(Request $request)
{
try {
$getTglmasuk = Karyawan::select('tglmasuk')
->where('id','=',$request->id_karyawan)->first();
// dd($request->id_karyawan,$getTglmasuk);
if(!$getTglmasuk) {
throw new \Exception('Data not found');
}
return response()->json($getTglmasuk,200);
} catch (\Exception $e){
return response()->json([
'message' =>$e->getMessage()
], 500);
}
}
public function getSettingalokasi(Request $request)
{
try {
$getSettingalokasi=Settingalokasi::select('id','id_jeniscuti','durasi','mode_alokasi')
->where('id_jeniscuti','=',$request->id_jeniscuti)->first();
if(!$getSettingalokasi) {
throw new \Exception('Data not found');
}
return response()->json($getSettingalokasi,200);
} catch (\Exception $e){
return response()->json([
'message' =>$e->getMessage()
], 500);
}
}
my Editalokasi.blade.php:
{{-- FORM SETTING ALOKASI--}}
<div class="modal fade" id="editalokasi{{$data->id}}" tabindex="-1" role="dialog" aria-
labelledby="editalokasi" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-
hidden="true">×</button>
<h4 class="modal-title" id="editalokasi">Edit Alokasi Cuti</h4>
</div>
<div class="modal-body">
<form class="input" action="/updatealokasi/{{$data->id}}" method="POST"
enctype="multipart/form-data">
#csrf
#method('POST')
<div class="panel-body">
<div class="col-md-6">
<div class="form-group col-sm">
<label for="id_jeniscuti" class="col-form-label">Kategori
Cuti</label>
<select name="id_jeniscuti" id="idjeniscuti" class="form-control">
<option value="{{$data->id_jeniscuti}}" selected>
{{$data->jeniscutis->jenis_cuti}}
</option>
#foreach ($jeniscuti as $jenis)
<option value="{{$jenis->id }}">{{ $jenis->jenis_cuti }}
</option>
#endforeach
</select>
</div>
<input type="text" class="form-control" name="durasi"
placeholder="durasi" id="idsettingalokasi" value="{{$data-
>id_settingalokasi}} --> id settingalokasi" readonly>
<input type="text" class="form-control" name="durasi"
placeholder="durasi" id="idjeniscutis" value="{{$data->id_jeniscuti}}
--> id kategori" readonly>
<input type="text" class="form-control" name="durasi"
placeholder="durasi" id="idjeniscutis" value="{{$data->id_karyawan}} -
->id karyawan" readonly>
<input type="text" class="form-control" name="durasi"
placeholder="durasi" id="idjeniscutis" value="{{$data->durasi}} Hari
--> durasi" readonly>
<input type="text" class="form-control" name="durasi"
placeholder="durasi" id="idjeniscutis" value="{{$data->mode_alokasi}}
-->mode alokasi" readonly>
<input type="text" class="form-control" name="durasi"
placeholder="durasi" id="idjeniscutis" value="
{{\Carbon\carbon::parse($data->aktif_dari)->format('m/d/Y')}} --
>aktif dari" readonly>
<input type="text" class="form-control" name="durasi"
placeholder="durasi" id="idjeniscutis" value="
{{\Carbon\carbon::parse($data->sampai)->format('m/d/Y')}} -->sampai tanggal"readonly>
<div class="form-group col-sm" id="idkaryawan">
<label for="id_karyawan" class="col-form-label">Karyawan</label>
<select name="id_karyawan" id="id_karyawan" class="form-control">
<option value="{{$data->id_karyawan}}" selected>{{$data->karyawans->nama}}</option>
#foreach ($karyawan as $data)
<option value="{{ $data->id }}">{{ $data->nama }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="durasi" class="col-form-label">Durasi (Hari)</label>
<input type="text" class="form-control" name="durasi" placeholder="durasi" id="duration" value="{{$data->durasi}}" readonly>
</div>
<div class="form-group">
<label for="mode_alokasi" class="col-form-label">Mode Alokasi</label>
<input type="text" class="form-control" name="mode_alokasi" placeholder="mode alokasi" value="{{$data->mode_alokasi}}" id="modealokasi" readonly>
</div>
</div>
<div class="col-md-6">
<div class="" id="tglmulai">
<div class="form-group">
<label for="tgl_masuk" class="form-label">Tanggal Masuk</label>
<div class="input-group">
<input type="text" class="form-control" placeholder="mm/dd/yyyy" id="tglmasuk" name="tgl_masuk" autocomplete="off" readonly>
<span class="input-group-addon bg-custom b-0"><i class="mdi mdi-calendar text-white"></i></span>
</div>
</div>
</div>
<div class="" id="tglnow">
<div class="form-group">
<label for="tgl_sekarang" class="form-label">Tanggal Sekarang</label>
<div class="input-group">
<input type="text" class="form-control" id="tglsekarang" name="tgl_sekarang" autocomplete="off" readonly>
<span class="input-group-addon bg-custom b-0"><i class="mdi mdi-calendar text-white"></i></span>
</div>
</div>
</div>
<div class="" id="tanggalmulai">
<div class="form-group">
<label for="tgl_mulai" class="form-label">Aktif Dari</label>
<div class="input-group">
<input type="text" class="form-control" placeholder="mm/dd/yyyy" id="datepicker-autoclosea3" name="aktif_dari" value="{{\Carbon\carbon::parse($data->aktif_dari)->format('m/d/Y')}}" autocomplete="off">
<span class="input-group-addon bg-custom b-0"><i class="mdi mdi-calendar text-white"></i></span>
</div>
</div>
</div>
<div class="" id="tanggalselesai">
<div class="form-group">
<label for="sampai" class="form-label">Sampai</label>
<div class="input-group">
<input type="text" class="form-control" placeholder="mm/dd/yyyy" id="datepicker-autoclosea4" name="sampai" value="{{\Carbon\carbon::parse($data->sampai)->format('m/d/Y')}}" autocomplete="off">
<span class="input-group-addon bg-custom b-0"><i class="mdi mdi-calendar text-white"></i></span>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-light" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-info" name="submit" value="save">Save Changes</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- jQuery -->
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/app.js"></script>
<script src="assets/pages/form-advanced.js"></script>
my Javascript:
<!-- script to fetch data settingalokasi from table settingalokasi -->
<script>
$('#idjeniscuti').on('change',function(e){
var id_jeniscuti = e.target.value;
$.ajaxSetup({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]')
.attr('content')
}
});
$.ajax({
type:"POST",
url: '{{route('get.Setting.alokasi')}}',
data: {'id_jeniscuti':id_jeniscuti},
success:function(data){
// console.log(data);
$('#idsettingalokasi').val(data.id);
$('#duration').val(data.durasi);
$('#modealokasi').val(data.mode_alokasi);
}
});
});
</script>
<!-- script to fetch data tanggal_masuk from table karyawan-->
<script>
$('#id_karyawan').on('change',function(e){
var id_karyawan = e.target.value;
$.ajaxSetup({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]')
.attr('content')
}
});
$.ajax({
type:"POST",
url: '{{route('get.Tanggalmasuk')}}',
data: {'id_karyawan':id_karyawan},
success:function(data){
// console.log(data);
$('#tgl_masuk').val(data.tglmasuk);
// console.log(data?.tglmasuk)
}
});
});
</script>
<script type="text/javascript">
$(function()
{
$('#tglmulai').prop("hidden", true);
$('#tglnow').prop("hidden", true);
$('#jenicuti').on('change', function(a)
{
if(a.target.value == 1)
{
$('#tglmulai').prop("hidden", false);
$('#tglnow').prop("hidden", false);
} else
{
$('#tglmulai').prop("hidden", true);
$('#tglnow').prop("hidden", true);
}
});
});
</script>
this is my first time using JQUERY AJAX for AUTOFILL. can anyone help me to solve this problem?

Unable insert in mysql table when I call another php

When I press register button in crudindex.php It will insert data in to cruduser(table)
once done Call crudadd.php and insert data into crud(table) with max(id) from cruduser table as id.
The issue is :Once I press REGISTER button Cruduser(table) is getting inserted properly.
But In crud(table) it inserts only the id and other fields are blank.
I have a doubt the post is not picking the values or insert command some issues.
But when I give static values ex : firstname as 'Tim', lastname as 'cook' etc its inserting in the table crud.
Also when I run crudadd.php separately it inserts properly.
Structure :
cruduser(
id(int),
username(varchar),
password(varchar)
)
crud(
id(int),
firstname(varchar),
lastname(varchar),
email(varchar),
gender(varchar),
age(varchar)
)
used : tables : cruduser and crud
php : crudindex.php and crudadd.php
Core issue : data is not properly inserted in to crud table
Crudindex.php
<?php
$con = mysqli_connect("127.0.0.1", "kkits996_ganesh", "mysql123#", "kkits996_testmysql") or die("Error " . mysqli_error($con));
if (isset($_POST) && (!empty($_POST))){
$uname=mysqli_real_escape_string($con,$_POST["uname"]);
$pwd=mysqli_real_escape_string($con,$_POST["pwd"]);
$cpwd=mysqli_real_escape_string($con,$_POST["cpwd"]);
if (isset($_POST['register'])) {
# Register-button was clicked
$createsql1="INSERT INTO cruduser(id,username,password) VALUES
('','$uname','$pwd')";
if (mysqli_query($con,$createsql1)) {
echo "Insert Successful in Table cruduser";
mysqli_close($con);
include ("crudadd.php");
}
else
{
die(mysqli_error($con));
}
}
mysqli_close($con);
}
?>
<!--DocType HTML -->
<! bootstrap link is downloaded from bootstrapcdn.com for css and js -->
<! col-mod-6 col-mod-offset are bootstrap related-->
<HTML>
<head>
<title>"Add records in CRUD Table"</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<form method="post" class="form-horizontal col-mod-6 col-mod-offset-3">
<h2>Create The table CRUD</h2>
<div class="form-group">
<label for="input" class="col-sm-2 control-label">Firstname</label>
<div class="col-sm-10">
<input type="text" name="uname" class="form-control" id="input1" placeholder="Username"/>
</div>
</div>
<div class="form-group">
<label for="input" class="col-sm-2 control-label">Lastname</label>
<div class="col-sm-10">
<input type="text" name="pwd" class="form-control" id="input1" placeholder="Password"/>
</div>
</div>
<div class="form-group">
<label for="input" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input type="text" name="cpwd" class="form-control" id="input1" placeholder="Confirm Password"/>
</div>
</div>
<div class="row">
<div class="col-mod-6 col-mod-offset-3">
<button id="submit1" name="register" class="btn btn-primary pull-right">Register</button>
<button id="submit2" name="login" class="btn btn-secondary pull-right">Login</button>
</div>
</div>
</form>
</body>
</html>
Crudadd.php
<?php
//session_start();
//$maxiid = $_SESSION['id'];
//echo $maxiid;
$con = mysqli_connect("127.0.0.1", "kkits996_ganesh", "mysql123#", "kkits996_testmysql") or die("Error " . mysqli_error($con));
$result = mysqli_query($con,"SELECT * FROM cruduser WHERE id=(SELECT MAX(id) FROM cruduser)");
$row1 = mysqli_fetch_array($result);
$c1 = $row1['id'];
mysqli_close($con);
$con = mysqli_connect("127.0.0.1", "kkits996_ganesh", "mysql123#", "kkits996_testmysql") or die("Error " . mysqli_error($con));
if (isset($_POST) && (!empty($_POST))){
$fname=mysqli_real_escape_string($con,$_POST["fname"]);
$lname=mysqli_real_escape_string($con,$_POST["lname"]);
$email=mysqli_real_escape_string($con,$_POST["email"]);
$gender=$_POST["gender"];
$age=$_POST["age"];
print "I am here";
echo $finame;
echo $liname;
print email;
//Notes : In Insert if numeric do not use quotes. if string use quotes.for auto use ''
$createsql="INSERT INTO crud(id,firstname,lastname,email,gender,age) VALUES
($c1,'$fname','$lname','$email','$gender','$age')";
if (mysqli_query($con,$createsql)) {
echo "Connection Successful";
}
else
{
echo "Connection Issue";
die(mysqli_error($con));
}
mysqli_close($con);
}
?>
<!--DocType HTML -->
<! bootstrap link is downloaded from bootstrapcdn.com for css and js -->
<! col-mod-6 col-mod-offset are bootstrap related-->
<HTML>
<head>
<title>"Add records in CRUD Table"</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<form method="post" class="form-horizontal col-mod-6 col-mod-offset-3">
<h2>Create The table CRUD</h2>
<div class="form-group">
<label for="input" class="col-sm-2 control-label">Firstname</label>
<div class="col-sm-10">
<input type="text" name="finame" class="form-control" id="input1" placeholder="First name"/>
</div>
</div>
<div class="form-group">
<label for="input" class="col-sm-2 control-label">Lastname</label>
<div class="col-sm-10">
<input type="text" name="liname" class="form-control" id="input1" placeholder="Last name"/>
</div>
</div>
<div class="form-group">
<label for="input" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input type="text" name="eimail" class="form-control" id="input1" placeholder="Email"/>
</div>
</div>
<div class="form-group">
<label for="input" class="col-sm-2 control-label">Gender</label>
<div class="col-sm-10">
<label>
<input type="radio" name="giender" id="optionsRadios1" value="male" checked> Male
</label>
<label>
<input type="radio" name="giender" id="optionsRadios1" value="female" > Female
</label>
</div>
</div>
<div class="form-group">
<label for="input" class="col-sm-2 control-label">Age</label>
<div class="col-sm-10">
<select name="aige" class="form-control">
<option>Select your age</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
<option value="24">24</option>
<option value="25">25</option>
<option value="26">26</option>
</select>
</div>
</div>
<input type="submit" class="btn btn=primary col-md-2 col-md-offset-10" value="submit"/>
</form>
</body>
</html>
While clicking on 'Register' you are sending uname, pwd and cpwd ina POST request which are properly used to be inserted into cruduser. After that you are including the crudadd.php (include ("crudadd.php");). But remember you are still at the same request. So the only data available is uname, pwd and cpwd. This is why your rows are semi-empty.
if Id is AUTO INCREMENT.
you must use
$createsql1="INSERT INTO cruduser(id,username,password) VALUES
(NULL,'$uname','$pwd')";
not ((you can not set string for id value. Your id is of int type ))
$createsql1="INSERT INTO cruduser(id,username,password) VALUES
('','$uname','$pwd')";

getting total value after entering the values in the form and inserting into database using codeigniter

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>

post multiple fields with same name

I have a form by multiple field. In this form i can add multiple group field by prese a button via javascript. To understand exactly what I mean please see fiddle:
https://jsfiddle.net/alihesari/060ym890/2/
How to get all added fields by php and insert theme in mysql after submit?
<fomr action="">
<button type="button" id="add_hotel" class="btn btn-primary">
Add Hotel</button>
<button type="button" id="remove_hotel" class="btn btn-warning">Remove Hotel</button>
<ul class="hotels_ul">
<li class="hotel_li">
<div class="row">
<div class="col-md-10">
<div class="form-group">
<label for="hotel_name[]">Hotel Name:</label>
<input type="text" name="hotel_name[]" id="hotel_name[]" class="form-control" placeholder="Hotel Name">
</div>
</div>
<div class="col-md-10">
<div class="form-group">
<label for="hotelRate[]">Hotel Rate: </label>
<select name="hotelRate[]" id="hotelRate[]" class="form-control">
<option value=""></option>
<option value="متل">متل</option>
<option value="یک ستاره">یک ستاره</option>
<option value="دو ستاره">دو ستاره</option>
<option value="سه ستاره">سه ستاره</option>
<option value="سه ستاره تاپ">سه ستاره تاپ</option>
<option value="چهار ستاره">چهار ستاره</option>
<option value="چهار ستاره تاپ">چهار ستاره تاپ</option>
<option value="پنج ستاره">پنج ستاره</option>
<option value="پنج ستاره تاپ">پنج ستاره تاپ</option>
<option value="هفت ستاره">هفت ستاره</option>
<option value="هتل آپارتمان">هتل آپارتمان</option>
</select>
</div>
</div>
<div class="col-md-10">
<div class="form-group">
<label for="room1[]">Room 1</label>
<input name="room1[]" id="room1[]" value="" class="form-control" placeholder="Price">
</div>
</div>
<div class="col-md-10">
<div class="form-group">
<label for="room2[]">Room 2</label>
<input name="room2[]" id="room2[]" value="" class="form-control" placeholder="Price">
</div>
</div>
<div class="col-md-10">
<div class="form-group">
<label for="room3[]">Room 3</label>
<input name="room3[]" id="room3[]" value="" class="form-control" placeholder="Price">
</div>
</div>
<div class="col-md-10">
<div class="form-group">
<label for="room4[]">Room 4</label>
<input name="room4[]" id="room4[]" value="" class="form-control" placeholder="Price">
</div>
</div>
<div class="col-md-20">
<div class="form-group">
<label for="desc[]">Description</label>
<textarea class="form-control" name="desc[]" id="desc[]" placeholder="Description"></textarea>
</div>
</div>
</div>
</li>
</ul>
<input type="submit" value="submit">
</form>
Here's an example of how you can handle the forms with both JS and PHP.
(if the JS example here doesn't work, see https://jsfiddle.net/n6kzxj4m/)
$(function() {
$(".add").on('click', function(e) {
$($(".hotel").last().clone(true, true)).insertAfter($(".hotel").last());
// reset new items
$(".hotel").last().find(':input:not(select)').not(':button, :submit, :reset, :hidden, :checkbox, :radio').val('');
$(".hotel").last().find('[select]').prop('selectedIndex', 0);
$(".hotel").last().find(':checkbox, :radio').prop('checked', false);
});
$(".remove").on('click', function(e) {
$(this).parents(".hotel").remove();
});
$("form").on('submit', function(e) {
e.preventDefault();
var $form = $(this);
$("#output").html($form.serializeJSON());
});
});
// plugin below only for debug on jsfiddle
/**
* jQuery serializeObject
* #copyright 2014, macek <paulmacek#gmail.com>
* #link https://github.com/macek/jquery-serialize-object
* #license BSD
* #version 2.4.5
*/
!function(e,r){if("function"==typeof define&&define.amd)define(["exports","jquery"],function(e,i){return r(e,i)});else if("undefined"!=typeof exports){var i=require("jquery");r(exports,i)}else r(e,e.jQuery||e.Zepto||e.ender||e.$)}(this,function(e,r){function i(e,i){function n(e,r,i){return e[r]=i,e}function a(e,r){for(var i,a=e.match(t.key);void 0!==(i=a.pop());)if(t.push.test(i)){var o=s(e.replace(/\[\]$/,""));r=n([],o,r)}else t.fixed.test(i)?r=n([],i,r):t.named.test(i)&&(r=n({},i,r));return r}function s(e){return void 0===h[e]&&(h[e]=0),h[e]++}function o(e){switch(r('[name="'+e.name+'"]',i).attr("type")){case"checkbox":return"on"===e.value?!0:e.value;default:return e.value}}function u(r){if(!t.validate.test(r.name))return this;var i=a(r.name,o(r));return c=e.extend(!0,c,i),this}function f(r){if(!e.isArray(r))throw new Error("formSerializer.addPairs expects an Array");for(var i=0,t=r.length;t>i;i++)this.addPair(r[i]);return this}function d(){return c}function l(){return JSON.stringify(d())}var c={},h={};this.addPair=u,this.addPairs=f,this.serialize=d,this.serializeJSON=l}var t={validate:/^[a-z_][a-z0-9_]*(?:\[(?:\d*|[a-z0-9_]+)\])*$/i,key:/[a-z0-9_]+|(?=\[\])/gi,push:/^$/,fixed:/^\d+$/,named:/^[a-z0-9_]+$/i};return i.patterns=t,i.serializeObject=function(){return this.length>1?new Error("jquery-serialize-object can only serialize one form at a time"):new i(r,this).addPairs(this.serializeArray()).serialize()},i.serializeJSON=function(){return this.length>1?new Error("jquery-serialize-object can only serialize one form at a time"):new i(r,this).addPairs(this.serializeArray()).serializeJSON()},"undefined"!=typeof r.fn&&(r.fn.serializeObject=i.serializeObject,r.fn.serializeJSON=i.serializeJSON),e.FormSerializer=i,i});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" action="#">
<fieldset class="hotel">
<legend>Add a hotel</legend>
<p><label>Hotel: <input type="text" name="hotel[name][]" /></label></p>
<p><label>Rate: <select name="hotel[rate][]"><option>123</option><option>456</option></select></label></p>
<p><input type="button" class="add" value="Add hotel" /> <input type="button" class="remove" value="Remove this hotel" /></p>
</fieldset>
<p><input type="submit" value="Search!" /></p>
</form>
<pre id="output"></pre>
Then, for the PHP handling, you can do:
<?php
if(!empty($_POST)) {
// handle items. $key is the index.
foreach($_POST['hotel']['name'] as $key => $hotel) {
$name = $hotel;
$rate = $_POST['hotel']['rate'][$key];
echo "Name: $name<br>Rate: $rate<hr>";
}
}
NOTE: You may want to check to ensure the number of items in $_POST['hotel']['name'] match the number of items in $_POST['hotel']['rate']. This method may not be ideal, and you may want to assign an ID per hotel row item via JS. But this is a basic approach to your question.

Populate form fields using json,php

im having a problem populating form fields.
When choosing value from doropdown fields in first line input fields are populated , i have 5 fields that are populated from database. To get those values im using:
".select_ttl" is a dropdown name attribute.
$(".select_ttl").change(function(event){
var kit=$(".select_ttl").val();
$.getJSON('/getanimation.php?kit=' + kit, null,
function(data)
{
$("#kit").val(data.kit);
$("#animation").val(data.animation);
$("#prix").val(data.prix);
});
});
the php file is:
<?php
require_once("inc/init.php");
require_once("inc/session.php");
require_once('inc/sql.php');
require_once("inc/config.ui.php");
header('Content-Type: application/json');
$title = $_GET["kit"]; // we received this from the json call
$Mysql = new Mysql();
$array_action = $Mysql->TabResSQL("SELECT * FROM liste_animation inner join kit ON liste_animation.ID_LISTE_ANIMATION=kit.ID_LISTE_ANIMATION where kit.CODE='".$title."' ");
foreach($array_action as $key){
$data = array(
'kit' => $key->CODE,
'animation' => $key->NOM_ANIMATION,
'prix' => $key->PRIX_ANIMATEUR,
);
}
echo (json_encode($data));
?>
Using this code i get only values for one row, in form there is an option to add a new line of input fields. So mu problem is how to do the same for multiple lines? Thanks in advance.
This is form example:
<div class="form-inline col-xs-2">
<select class="select_ttl form-control" name="kit" id="kit">
<option class='select_ttl' value="" selected="selected" disabled="disabled">Kit</option>
<?php
$Mysql = new Mysql();
$ArraySelect = $Mysql->TabResSQL('SELECT distinct KIT from kit_voyage');
foreach($ArraySelect as $key){
echo "<option value=".$key->KIT.">".$key->KIT."</option>";
?>
<?php } ?>
</select> <!-- end .select_ttl -->
</div>
<!-- Text input-->
<div class="form-group col-xs-3">
<input id="animation" name="animation" type="text" placeholder="nom animation" class="input_fn form-control" required="" value=''>
</div>
<!-- Text input-->
<div class="form-group col-xs-2">
<input id="prix" name="prix" type="text" placeholder="PU_HT" class="input_ln form-control" value=''>
</div>
<!-- Text input-->
<div class="form-group col-xs-2">
<input value="1" id="quantity" name="quantity" type="text" placeholder="qtité" class="input_email form-control">
</div>
<div class="form-group col-xs-2">
<input id="tva" name="tva" type="text" placeholder="TVA" class="input_email form-control">
</div>
<div class="form-group col-xs-2">
<input id="rem" name="rem" type="text" placeholder="REM" class="input_email form-control">
</div>
<div class="form-group col-xs-2">
<input id="totaltt" name="totaltt" type="text" placeholder="Total TT" class="input_email form-control">
</div>
Use
$(".select_ttl").change(function(event){
var kit=$(this).val();
});
& insted of echo (json_encode($data)); use echo json_encode($data); remove outter ()

Categories