OnChange Not Working in cloned Input fields - javascript

I have created a form and in the form I have given room to clone input fields ie add or delete rows.
In one input field I am using Jquery Ajax to get the value.
Unfortunately after adding an additional role ie cloning the parent row to get a child row, ajax does not pass the value for the input field expecting it value from the Ajax.
I have attached the code below to explain better
function restrictAlphabets(e) {
var x = e.which || e.keyCode;
if ((x >= 48 && x <= 57))
return true;
else
return false;
}
// Below Clones Table
document.querySelector('button[data-name="add"]').addEventListener('click', e => {
let tbody = e.target.closest('table').querySelector('tbody');
let clone = tbody.firstElementChild.cloneNode(true);
clone.querySelector('button[data-name="del"]').hidden = false;
clone.querySelectorAll('input, select').forEach(n => {
n.value = '';
});
tbody.appendChild(clone);
});
document.querySelector('form table#dyntbl').addEventListener('click', e => {
e.stopPropagation();
if (e.target != e.currentTarget && (e.target.dataset.name == 'del' || e.target.parentNode.dataset.name == 'del')) {
let tbody = e.target.closest('table').querySelector('tbody');
if (tbody.childNodes.length > 3) tbody.removeChild(e.target.closest('tr'))
}
});
// Below begins AJAX Function
function checkDeviceStatus() {
var dModel = $("#model").val();
var dBrand = $("#brand").val();
var dserial = $("#serialNo").val();
var client = $("#client").val();
$.ajax({
url: "./handlers/slaChecker.php",
type: "POST",
data: {
dModel: dModel,
dserial: dserial,
client: client,
dBrand: dBrand,
},
success: function(result) {
$("#deviceLevel").val(result);
console.log(result);
}
})
}
<div class="col-xl-8 col-md-12">
<form>
<div class="card">
<div class="card-header">
<h3 class="card-title"><strong class="text-success" style="cursor: pointer;"><?=ucwords($clientName)?></strong> REP'S INFORMATION</h3>
</div>
<div class="card-body">
<div class="row">
<div class="col-sm-4 col-md-4">
<div class="form-group">
<label class="form-label">Reps Name<span class="text-red">*</span></label>
<input type="text" name="" class="form-control" required="">
</div>
</div>
<div class="col-sm-4 col-md-4">
<div class="form-group">
<label class="form-label">E-Mail<span class="text-red">*</span></label>
<input type="email" name="" class="form-control" required="">
</div>
</div>
<div class="col-sm-4 col-md-4">
<div class="form-group">
<label class="form-label">Phone No.<span class="text-red">*</span></label>
<input type="text text-dark" class="form-control" name="client_contact2" required="" id="client_contact2" onkeypress="return restrictAlphabets(event)" onpaste="return false;" ondrop="return false;" autocomplete="off" required="">
<input type="date" name="" value="<?=date(" Y-m-d ")?>" hidden="">
</div>
</div>
</div>
</div>
</div>
<div class="card">
<div class="card-header">
<h3 class="card-title">ADD DEVICE(S) INFORMATION</h3>
</div>
<div class="card-body">
<?php
if ($clientType === $slaClient) {
?>
<table id='dyntbl' class='table border text-nowrap text-md-nowrap table-striped mb-0'>
<thead>
<tr>
<th class="text-center">Device Brand</th>
<th class="text-center">Device Model</th>
<th class="text-center">Serial Number</th>
<th class="text-center" style="width:10%">SLA Device</th>
<th><button type="button" class=" btn text-success" data-name='add'><i class="fe fe-plus-circle" data-id='ad' style="font-size:1.6em;"></i></button></th>
</tr>
</thead>
<tbody class="field_wrapper " id="table_body">
<tr>
<td>
<select class="form-control form-select " data-bs-placeholder="Select" name="brand[]" required="" id="brand" onchange="checkDeviceStatus()">
<?php
$readALL = "SELECT * FROM productbrands WHERE deleted = 0";
$displayAll = mysqli_query($conn,$readALL);
while($rowFetchAll = mysqli_fetch_array($displayAll)){
$brandName = $rowFetchAll['brandName'];
$brandid = $rowFetchAll['brandID'];
?>
<option value="<?=$brandid?>">
<?=$brandName?>
</option>
<?php } ?>
</select>
</td>
<td>
<select class="form-control form-select " data-bs-placeholder="Select" name="model[]" required="" id="model" onchange="checkDeviceStatus()">
<?php
$readALL1 = "SELECT * FROM productmodels WHERE deleted = 0";
$displayAll1 = mysqli_query($conn,$readALL1);
while($rowFetchAll1 = mysqli_fetch_array($displayAll1)){
$modelName = $rowFetchAll1['modelName'];
$modelid = $rowFetchAll1['modelID'];
?>
<option value="<?=$modelid?>">
<?=$modelName?>
</option>
<?php } ?>
</select>
</td>
<td><input type="text" name="serialNo" class="form-control" id="serialNo" onchange="checkDeviceStatus()"></td>
<!-- The input field below is to get value from AJAX -->
<td><input type="text" name="deviceLevel" class="form-control" readonly="" id="deviceLevel">
<!-- End of Input field -->
</td>
<input type="text" name="" id="client" value="<?=$clientID?>" hidden="">
<td><button type="button" class=" btn text-danger" data-name="del"><i class="fe fe-minus-circle" style="font-size:1.6em;"></i></button></td>
</tr>
</tbody>
</table>
<?php } ?>
<?php
if ($clientType === $nonSla) {
?>
<table id='dyntbl' class='table border text-nowrap text-md-nowrap table-striped mb-0'>
<thead>
<tr>
<th>Product Model Non-SLA</th>
<th>Serial Number Non-SLA</th>
<th>Device Status Non-SLA</th>
<th><button type="button" class=" btn text-success" data-name='add'><i class="fe fe-plus-circle" data-id='ad' style="font-size:1.6em;"></i></button></th>
</tr>
</thead>
<tbody class="field_wrapper " id="table_body">
<tr>
<td><input type="text" name="" class="form-control"></td>
<td><input type="text" name="" class="form-control"></td>
<td><input type="text" name="" class="form-control"></td>
<td><button type="button" class=" btn text-danger" data-name="del"><i class="fe fe-minus-circle" style="font-size:1.6em;"></i></button></td>
</tr>
</tbody>
</table>
<?php } ?>
</div>
</div>
</form>
</div>

The main problem is that when you clone, you will get duplicated id's. An Id must always be unique.
I would suggest that you change the ID to class or something else and do something like this.
function checkDeviceStatus(obj) {
var dModel = $(obj).closest("tr").find(".model").val();
var dBrand = $(obj).closest("tr").find(".brand").val();
var dserial = $(obj).closest("tr").find(".serialNo").val();
var client = $(obj).closest("tr").find(".client").val();
console.log("dserial:"+dserial);
//Removed ajax for demo.
}
And then add this to your onchange="checkDeviceStatus()" like onchange="checkDeviceStatus(this)"
Demo
function restrictAlphabets(e) {
var x = e.which || e.keyCode;
if ((x >= 48 && x <= 57))
return true;
else
return false;
}
// Below Clones Table
document.querySelector('button[data-name="add"]').addEventListener('click', e => {
let tbody = e.target.closest('table').querySelector('tbody');
let clone = tbody.firstElementChild.cloneNode(true);
clone.querySelector('button[data-name="del"]').hidden = false;
clone.querySelectorAll('input, select').forEach(n => {
n.value = '';
});
tbody.appendChild(clone);
});
document.querySelector('form table#dyntbl').addEventListener('click', e => {
e.stopPropagation();
if (e.target != e.currentTarget && (e.target.dataset.name == 'del' || e.target.parentNode.dataset.name == 'del')) {
let tbody = e.target.closest('table').querySelector('tbody');
if (tbody.childNodes.length > 3) tbody.removeChild(e.target.closest('tr'))
}
});
// Below begins AJAX Function
function checkDeviceStatus(obj) {
var dModel = $(obj).closest("tr").find(".model").val();
var dBrand = $(obj).closest("tr").find(".brand").val();
var dserial = $(obj).closest("tr").find(".serialNo").val();
var client = $(obj).closest("tr").find(".client").val();
console.log("dserial:"+dserial);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-xl-8 col-md-12">
<form>
<div class="card">
<div class="card-header">
<h3 class="card-title"><strong class="text-success" style="cursor: pointer;"><?=ucwords($clientName)?></strong> REP'S INFORMATION</h3>
</div>
<div class="card-body">
<div class="row">
<div class="col-sm-4 col-md-4">
<div class="form-group">
<label class="form-label">Reps Name<span class="text-red">*</span></label>
<input type="text" name="" class="form-control" required="">
</div>
</div>
<div class="col-sm-4 col-md-4">
<div class="form-group">
<label class="form-label">E-Mail<span class="text-red">*</span></label>
<input type="email" name="" class="form-control" required="">
</div>
</div>
<div class="col-sm-4 col-md-4">
<div class="form-group">
<label class="form-label">Phone No.<span class="text-red">*</span></label>
<input type="text text-dark" class="form-control" name="client_contact2" required="" id="client_contact2" onkeypress="return restrictAlphabets(event)" onpaste="return false;" ondrop="return false;" autocomplete="off" required="">
<input type="date" name="" value="<?=date(' Y-m-d ')?>" hidden="">
</div>
</div>
</div>
</div>
</div>
<div class="card">
<div class="card-header">
<h3 class="card-title">ADD DEVICE(S) INFORMATION</h3>
</div>
<div class="card-body">
<?php
if ($clientType === $slaClient) {
?>
<table id='dyntbl' class='table border text-nowrap text-md-nowrap table-striped mb-0'>
<thead>
<tr>
<th class="text-center">Device Brand</th>
<th class="text-center">Device Model</th>
<th class="text-center">Serial Number</th>
<th class="text-center" style="width:10%">SLA Device</th>
<th><button type="button" class=" btn text-success" data-name='add'><i class="fe fe-plus-circle" data-id='ad' style="font-size:1.6em;">ADD</i></button></th>
</tr>
</thead>
<tbody class="field_wrapper " id="table_body">
<tr>
<td>
<select class="form-control form-select brand" data-bs-placeholder="Select" name="brand[]" required="" id="" onchange="checkDeviceStatus(this)">
<?php
$readALL = "SELECT * FROM productbrands WHERE deleted = 0";
$displayAll = mysqli_query($conn,$readALL);
while($rowFetchAll = mysqli_fetch_array($displayAll)){
$brandName = $rowFetchAll['brandName'];
$brandid = $rowFetchAll['brandID'];
?>
<option value="<?=$brandid?>">
<?=$brandName?>
</option>
<?php } ?>
</select>
</td>
<td>
<select class="form-control form-select model" data-bs-placeholder="Select" name="model[]" required="" id="" onchange="checkDeviceStatus(this)">
<?php
$readALL1 = "SELECT * FROM productmodels WHERE deleted = 0";
$displayAll1 = mysqli_query($conn,$readALL1);
while($rowFetchAll1 = mysqli_fetch_array($displayAll1)){
$modelName = $rowFetchAll1['modelName'];
$modelid = $rowFetchAll1['modelID'];
?>
<option value="<?=$modelid?>">
<?=$modelName?>
</option>
<?php } ?>
</select>
</td>
<td><input type="text" name="serialNo" class="form-control serialNo" onchange="checkDeviceStatus(this)"></td>
<!-- The input field below is to get value from AJAX -->
<td><input type="text" name="deviceLevel" class="form-control" readonly="" id="deviceLevel">
<!-- End of Input field -->
</td>
<input type="text" name="" class="client" value="<?=$clientID?>" hidden="">
<td><button type="button" class=" btn text-danger" data-name="del"><i class="fe fe-minus-circle" style="font-size:1.6em;"></i></button></td>
</tr>
</tbody>
</table>
<?php } ?>
<?php
if ($clientType === $nonSla) {
?>
<table id='dyntbl' class='table border text-nowrap text-md-nowrap table-striped mb-0'>
<thead>
<tr>
<th>Product Model Non-SLA</th>
<th>Serial Number Non-SLA</th>
<th>Device Status Non-SLA</th>
<th><button type="button" class=" btn text-success" data-name='add'><i class="fe fe-plus-circle" data-id='ad' style="font-size:1.6em;"></i></button></th>
</tr>
</thead>
<tbody class="field_wrapper " id="table_body">
<tr>
<td><input type="text" name="" class="form-control"></td>
<td><input type="text" name="" class="form-control"></td>
<td><input type="text" name="" class="form-control"></td>
<td><button type="button" class=" btn text-danger" data-name="del"><i class="fe fe-minus-circle" style="font-size:1.6em;"></i></button></td>
</tr>
</tbody>
</table>
<?php } ?>
</div>
</div>
</form>
</div>

I have found solution to it.
The classes as you all suggested wasn't Ideal instead this is what I did.
the ids has to be unique so I created a variable for it to be handling the additional ids.
This worked perfectly for me.
Php is now working fine and Ajax is also working fine.
$(document).ready(function() {
var num = 1;
var c = `
<tr id="row_num" >
<td>
<select class="form-control form-select brand" data-bs-placeholder="Select" name="brand[]" required="" id="brand_num" onchange="checkDeviceStatus(_num)">
<?php
$readALL = "SELECT * FROM productbrands WHERE deleted = 0";
$displayAll = mysqli_query($conn,$readALL);
while($rowFetchAll = mysqli_fetch_array($displayAll)){
$brandName = $rowFetchAll['brandName'];
$brandid = $rowFetchAll['brandID'];
?>
<option value="<?=$brandid?>"><?=$brandName?></option>
<?php } ?>
</select>
</td>
<td>
<select class="form-control form-select model" data-bs-placeholder="Select" name="model[]" required="" id="model_num" onchange="checkDeviceStatus(_num)">
<?php
$readALL1 = "SELECT * FROM productmodels WHERE deleted = 0";
$displayAll1 = mysqli_query($conn,$readALL1);
while($rowFetchAll1 = mysqli_fetch_array($displayAll1)){
$modelName = $rowFetchAll1['modelName'];
$modelid = $rowFetchAll1['modelID'];
?>
<option value="<?=$modelid?>"><?=$modelName?></option>
<?php } ?>
</select>
</td>
<td><input type="text" name="serialNo" class="form-control serialNo" id="serialNo_num" onkeyup="checkDeviceStatus(_num)"></td>
<!-- The input field below is to get value from AJAX -->
<td>
<input type="text" name="deviceLevel" class="form-control " readonly="" id="deviceLevel_num">
<!-- End of Input field -->
</td>
<td><button type="button" onclick="DeleteRow(_num)" class=" btn text-danger remove" data-name="del"><i class="fe fe-minus-circle" style="font-size:1.6em;"></i></button></td>
</tr>
`;
$(".addRow").click(function(e) {
var cc = c;
// e.preventDefault();
cc = cc.replace('_num', num);
cc = cc.replace('_num', num);
cc = cc.replace('_num', num);
cc = cc.replace('_num', num);
cc = cc.replace('_num', num);
cc = cc.replace('_num', num);
cc = cc.replace('_num', num);
cc = cc.replace('_num', num);
cc = cc.replace('_num', num);
$(".table_body").append(cc);
num++;
console.log(num);
});
});
<tbody class="field_wrapper showRow table_body" id="table_body">
<tr id="row0">
<td>
<select class="form-control form-select" data-bs-placeholder="Select" name="brand[]" required="" id="brand0" onchange="checkDeviceStatus(0)">
<?php
$readALL = "SELECT * FROM productbrands WHERE deleted = 0";
$displayAll = mysqli_query($conn,$readALL);
while($rowFetchAll = mysqli_fetch_array($displayAll)){
$brandName = $rowFetchAll['brandName'];
$brandid = $rowFetchAll['brandID'];
?>
<option value="<?=$brandid?>">
<?=$brandName?>
</option>
<?php } ?>
</select>
</td>
<td>
<select class="form-control form-select " data-bs-placeholder="Select" name="model[]" required="" id="model0" onchange="checkDeviceStatus(0)">
<?php
$readALL1 = "SELECT * FROM productmodels WHERE deleted = 0";
$displayAll1 = mysqli_query($conn,$readALL1);
while($rowFetchAll1 = mysqli_fetch_array($displayAll1)){
$modelName = $rowFetchAll1['modelName'];
$modelid = $rowFetchAll1['modelID'];
?>
<option value="<?=$modelid?>">
<?=$modelName?>
</option>
<?php } ?>
</select>
</td>
<td><input type="text" name="serialNo" class="form-control " id="serialNo0" onkeyup="checkDeviceStatus(0)"></td>
<!-- The input field below is to get value from AJAX -->
<td><input type="text" name="deviceLevel" class="form-control " readonly="" id="deviceLevel0">
<!-- End of Input field -->
</td>
<input type="text" name="" id="client" value="<?=$clientID?>" hidden="">
<td><button type="button" class=" btn text-success addRow" data-name='add'><i class="fe fe-plus-circle " data-id='ad' style="font-size:1.6em;"></i></button></td>
</tr>
</tbody>

Related

Dynamic row calculation with Jquery

I want to make sum of dynamic rows and addition.
<div class="row">
<div class="col-md-8">
<div class="table-responsive">
<table id="test-table" class="table table-bordered">
<thead>
<tr>
<th>Product</th>
<th>Price </th>
<th><input id='add-row' class='btn btn-primary' type='button' value='Add' /> </th>
</tr>
</thead>
<tbody id="test-body">
<tr id="row0" class="products">
<td>
<select name="product_id[]" id="" class="form-control">
<option value="">-- Select Product --</option>
#foreach ($product as $row )
<option value="{{ $row->id }}">{{ $row->product_name }}</option>
#endforeach
</select>
</td>
<td>
<input name="price[]" type="number" min="1" class="form-control input-md price" />
</td>
<td>
<input class="delete-row btn btn-primary" type="button" value="Delete" />
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="col-md-4">
<div class="col-xs-6">
<p>Previous Due</p>
</div>
<div class="col-xs-6">
<input type="text" class="form-control" value="5000" readonly>
</div>
<div class="col-xs-6">
<p>Total Price</p>
</div>
<div class="col-xs-6">
<input type="text" class="form-control total_price" value="" readonly>
</div>
<div class="col-xs-6">
<p>Pay Now</p>
</div>
<div class="col-xs-6">
<input type="number" class="form-control">
</div>
<div class="col-xs-6">
<p>Total Due</p>
</div>
<div class="col-xs-6">
<input type="number" value="" class="form-control">
</div>
</div>
</div>
Script:
<script type="text/javascript">
var row=1;
$(document).on("click", "#add-row", function () {
var new_row = '<tr id="row' + row + '" class="products"><td> <select name="product_id[]' + row + '" id="" class="form-control"> <option value="">-- Select Product --</option> #foreach ($product as $row ) <option value="{{ $row->id }}">{{ $row->product_name }}</option>#endforeach </select></td><td><input name="price[]' + row + '" type="number" min="1" class="form-control price" /></td><td><input class="delete-row btn btn-primary" type="button" value="Delete" /></td></tr>';
$('#test-body').append(new_row);
row++;
return false;
});
$(document).on("click", ".delete-row", function () {
if(row>0) {
$(this).closest('tr').remove();
row--;
}
return false;
});
</script>
<script type="text/javascript">
function sumIt() {
var total = 0, val;
$('.price').each(function() {
val = $(this).val();
val = isNaN(val) || $.trim(val) === "" ? 0 : parseFloat(val);
total += val;
});
$('.total_price').val(Math.round(total));
}
$(function() {
$(document).on('input', '.price', sumIt);
sumIt()
});
</script>
If I delete product row, the total price field is not updating the calculation. Suppose I added 4 rows, and give price value, after that I remove two rows, but the total price holds the previous 4 rows sum, it didn't update when I remove any row.
Here I want to show the total sum of product in total price.
And the Total Due calculation will be total due = (previous due + total price)- pay now
thanks

How to access parent element and then get it's value and then append to other element when adding a row?

My goal is to get the previous value inside my input element labeled "SERIAL END" then automatically append it's value when adding a row to "SERIAL START" and not only append but will add +1 to it's value. The problem is I always get an undefine value, I don't know what is missing.
Here is the image
Here is the snippets
$(document).ready(function() {
$("#addrow").on("click", function() {
var startElement = $("#start");
var value = parseInt(startElement.val());
startElement.val(value);
var hidden = startElement.val();
var tbl = document.getElementById('tbl').rows.length;
if (tbl === 5) {
alert("It is limited for 5 rows only");
} else {
var newRow = $("<tr id='tablerow_" + hidden + "'>");
var cols = "";
cols +=
'<td><select onchange="selectmodel(this)"data-live-search="true" placeholder="Select your model name"id="model' +
hidden + '" class="form-control selectpicker show-menu-arrow " name="model[]" ><option selected disabled> Select your model name</option><?php $sql = mysqli_query($con,"call gettrial");
if(mysqli_num_rows($sql)>0){
while($row=mysqli_fetch_assoc($sql)){
echo "<option value=$row[id]>".$row['model_name']." </option>";
}
} ?></select></td>';
cols +=
'<td><input id="code' + hidden +
'" value="" type="text" class="form-control" name="code[]" readonly="" /></td>';
cols +=
'<td><input type="number" class="form-control" id="serstart' + hidden +
'" name="serstart[]" readonly/></td>';
cols +=
'<td><input type="number" class="form-control" id="serend' + hidden +
'" name="serend[]" onkeyup="manage(this)" /></td>';
newRow.append(cols);
$("table.order-list").append(newRow)
.find('.selectpicker')
.selectpicker({
liveSearch: true,
showSubtext: true
});
const hide = document.getElementById('start');
hide.value = (parseInt(hidden) + parseInt(1));
hidden++;
}
});
$('#remove').click(function() {
$("#myTable").each(function() {
if ($('tr', this).length > 2) {
$('tr:last', this).remove();
}
});
});
});
$('#addrow').click(function() {
var id = $(this).closest('tr').find('#tablerow_0').text();
var row = $(this).parent("tbody tr");
var rowin=$(this).parent('tr').find('input:number');
var rowprev=$(this).parent('tr').prev().find('input:last').val();
var rownext=$(this).parent('tr').next().find('input:first').val();
console.log($(this).parent('tr').prev().find('input:last'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-lg-12">
<form class="className" name="form" id="form"
action="lot_registration_model_submit.php" data-toggle="validator"
enctype="multipart/form-data" method="POST">
<div class="form-group">
<label class="col-sm-3">Lot No.: <font color="red">*</font></label>
<div class="col-sm-9">
<input autocomplete="off" class="form-control" type="text" id="lotno"
name="lotno" style="text-transform:uppercase" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-3">Month of: <font color="red">*</font></label>
<div class="col-sm-9">
<input autocomplete="off" class="form-control" type="date" id="monthof"
name="monthof" style="text-transform:uppercase" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-3">Serial Start: <font color="red">*</font></label>
<div class="col-sm-9">
<input autocomplete="off" class="form-control" type="number" id="serstart" name="serstart"
style="text-transform:uppercase" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-3">Serial End: <font color="red">*</font></label>
<div class="col-sm-9">
<input autocomplete="off" class="form-control" type="number" id="serend"
name="serend" style="text-transform:uppercase" required>
</div>
</div>
<input type="button" class="btn btn-primary pull-left" id="addrow" value="Add Row" disabled />
<input type="button" class="ibtnDel btn btn-md btn-danger" id="remove" value="Delete Row">
<br>
<table width="100%" class="table order-list table-striped table-bordered table-hover"
id="myTable">
<thead>
<tr>
<th class="col-sm-3">
<center />Model
</th>
<th class="col-sm-3">
<center />Code
</th>
<th class="col-sm-3">
<center />Serial Start
</th>
<th class="col-sm-3">
<center />Serial End
</th>
</tr>
</thead>
<tbody id='tbl'>
<tr id="tablerow_0">
<td>
<select name="model[]" id="model0" class="form-control selectpicker show-menu-arrow"
data-live-search="true" title="Select your model name"
onchange="selectmodel(this)" required>
<?php
$sql = mysqli_query($con,"SELECT model.id,model.model_name,model.code,model.status
FROM model left join grouped on model.id = grouped.modelandcode
WHERE cat_id='1' and model.status='1' and grouped.status is null
ORDER BY model_name ASC");
$con->next_result();
if(mysqli_num_rows($sql)>0)
{
while($row=mysqli_fetch_assoc($sql))
{
echo "<option value='".$row['id']."'>".$row['model_name']."</option>";
}
}
?>
</select>
</td>
<td>
<input name="code[]" type="text" id="code0" value="" class="form-control" readonly="" />
</td>
<td>
<input type="number" name="serstart[]" id="serstart0" class="form-control" readonly />
</td>
<td>
<input type="number" name="serend[]" id="serend0" class="form-control"
</td>
</tr>
</tbody>
</table>
<input type="hidden" value="1" id="start" />
<button id="submit" type="submit" class="btn btn-primary pull-right"><span
class="fa fa-check"> &nbsp Submit</span></button>
</form>
</div>
You can get length of tr inside tbody then using that length get reference of previous tr then use td:eq(3) this will search fourth td because index starts from 0 then use that value to get value and add it in newly created tr input .
Also , you don't need to use same php code to create select-box just clone first select-box and then use same to pass inside td which are newly created .
Then , to intialize selectpicker which are added dynamically use $("table.order-list tr:last").find(".selectpicker").. this line will get last tr which is added and then inside that tr it will selectpicker .
Demo Code :
$(document).ready(function() {
$('.selectpicker').selectpicker({
liveSearch: true,
showSubtext: true
});
$("#addrow").on("click", function() {
var cloned = $("tbody select:first").clone() //cloned first tr select
var value = $("tbody tr").length - 1 //get tr length - 1 (because tr start from 0 index)
var new_start = parseInt($("tbody tr:eq(" + value + ") td:eq(3) input").val()) + 1 //get previous input box value
var tbl = document.getElementById('tbl').rows.length;
if (tbl === 5) {
alert("It is limited for 5 rows only");
} else {
var newRow = $("<tr id='tablerow_'" + (value + 1) + "'>");
var cols = "";
cols += '<td><select onchange="selectmodel(this)"data-live-search="true" placeholder="Select your model name" class="form-control selectpicker show-menu-arrow " name="model[]" >' + $(cloned).html() + '</select></td>';
cols += '<td><input value="' + $("#lotno").val() + '" type="text" class="form-control" name="code[]" readonly="" /></td>';
cols +=
'<td><input type="number" class="form-control" name="serstart[]" value="' + new_start + '" readonly/></td>';
cols +=
'<td><input type="number" class="form-control"name="serend[]" value="' + $("#serend").val() + '"/></td>';
newRow.append(cols);
$("table.order-list").append(newRow)
//intialize selectpicker which added last
$("table.order-list tr:last").find('.selectpicker').selectpicker({
liveSearch: true,
showSubtext: true
});
}
});
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.18/css/bootstrap-select.min.css" integrity="sha512-ARJR74swou2y0Q2V9k0GbzQ/5vJ2RBSoCWokg4zkfM29Fb3vZEQyv0iWBMW/yvKgyHSR/7D64pFMmU8nYmbRkg==" crossorigin="anonymous"
/>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.18/js/bootstrap-select.min.js" integrity="sha512-yDlE7vpGDP7o2eftkCiPZ+yuUyEcaBwoJoIhdXv71KZWugFqEphIS3PU60lEkFaz8RxaVsMpSvQxMBaKVwA5xg==" crossorigin="anonymous"></script>
<div class="col-lg-12">
<input type="button" class="btn btn-primary pull-left" id="addrow" value="Add Row" />
<input type="button" class="ibtnDel btn btn-md btn-danger" id="remove" value="Delete Row">
<br>
<table width="100%" class="table order-list table-striped table-bordered table-hover" id="myTable">
<thead>
<tr>
<th class="col-sm-3">
<center />Model
</th>
<th class="col-sm-3">
<center />Code
</th>
<th class="col-sm-3">
<center />Serial Start
</th>
<th class="col-sm-3">
<center />Serial End
</th>
</tr>
</thead>
<tbody id='tbl'>
<tr id="tablerow_0">
<td>
<select name="model[]" id="model0" class="form-control selectpicker show-menu-arrow" data-live-search="true" title="Select your model name" onchange="selectmodel(this)" required>
<option selected disabled> Select your model name</option>
<option value='1'>A</option>
<option value='2'>A2</option>
<option value='3'>A3</option>
</select>
</td>
<td>
<input name="code[]" type="text" id="code0" value="M12" class="form-control" readonly="" />
</td>
<td>
<input type="number" name="serstart[]" id="serstart0" value="1" class="form-control" readonly />
</td>
<td>
<input type="number" name="serend[]" id="serend0" value="11" class="form-control"> </td>
</tr>
</tbody>
</table>
<button id="submit" type="submit" class="btn btn-primary pull-right"><span
class="fa fa-check"> &nbsp Submit</span></button>
</form>
</div>

How to make a dynamic change and access a parent element on a value using JQuery?

I have a form where it is related to my previous question here. What I want to do is to get the previous value inside my input element labeled "SERIAL END" then automatically appends it's value when adding a row to "SERIAL START", and not only append but will add +1 to it's value (this is solved), but I want to add a function when the value is already added, it will get the value of the edited parent element and can be changeable but still adds the children element's value by +1.
Here is my whole code
$(document).ready(function() {
$("#addrow").on("click", function() {
var startElement = $("#start");
var value = parseInt(startElement.val());
startElement.val(value);
var hidden = startElement.val();
var tbl = document.getElementById('tbl').rows.length;
if (tbl === 5) {
alert("It is limited for 5 rows only");
} else {
var lasttr = $('#tbl tr:last').attr('id');
var lastinsertedrow = lasttr.replace('tablerow_', '');
var end = $('#serend' + lastinsertedrow).val();
end = (parseInt(end) + parseInt(1));
var newRow = $("<tr id='tablerow_" + hidden + "'>");
var cols = "";
cols +=
'<td><select onchange="selectmodel(this)"data-live-search="true" placeholder="Select your model name"id="model' +
hidden + '" class="form-control selectpicker show-menu-arrow " name="model[]" required><option selected disabled> Select your model name</option><?php $sql = mysqli_query($con,"call gettrial");
if (mysqli_num_rows($sql) > 0) {
while ($row = mysqli_fetch_assoc($sql)) {
echo "<option value=$row[id]>".$row['model_name'].
" </option>";
}
} ? > < /select></td > ';
cols +=
'<td><input id="code' + hidden +
'" value="" type="text" class="form-control" name="code[]" readonly="" /></td>';
cols +=
'<td><input type="text" class="form-control" id="serstart' + hidden +
'" name="serstart[]" value="' + end + '" readonly/></td>';
cols +=
'<td><input type="text" class="form-control" id="serend' + hidden +
'" name="serend[]" onchange="myChangeFunction(this)" required /></td>';
newRow.append(cols);
$("table.order-list").append(newRow)
.find('.selectpicker')
.selectpicker({
liveSearch: true,
showSubtext: true
});
$("#serend" + hidden).on("change", function(e) {
var x = $("#serend").val()
if ($(this).val() > (x * 100) / 100) {
alert("You exceed in " + x + " pls do enter below or exact " + x)
}
})
const hide = document.getElementById('start');
hide.value = (parseInt(hidden) + parseInt(1));
hidden++;
}
});
$('#remove').click(function() {
$("#myTable").each(function() {
if ($('tr', this).length > 2) {
$('tr:last', this).remove();
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<?php
include ('../include/header_pis.php');
?>
<html>
<title>Lot_Registration</title>
<body>
<div id="wrapper">
<div id="page-wrapper">
<div class="row">
<div class="col-lg-12">
<h1 class="page-header"> Lot Registration
<a href="rbg_table.php">
<button class="btn btn-success pull-right">
<span class="fa fa-reply"> Back </span>
</button>
</a>
</h1>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<div class="panel panel-primary">
<div class="panel-heading">
Model Form
</div>
<div class="panel-body">
<div class="row">
<div class="col-lg-12">
<form class="className" name="form" id="form" action="lot_registration_model_submit.php" data-toggle="validator" enctype="multipart/form-data" method="POST">
<div class="form-group">
<label class="col-sm-3">Lot No.: <font color="red">*</font></label>
<div class="col-sm-9">
<input autocomplete="off" class="form-control" type="text" id="lotno" name="lotno" style="text-transform:uppercase" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-3">Month of: <font color="red">*</font></label>
<div class="col-sm-9">
<input autocomplete="off" class="form-control" type="date" id="monthof" name="monthof" style="text-transform:uppercase" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-3">Serial Start: <font color="red">*</font></label>
<div class="col-sm-9">
<input autocomplete="off" class="form-control" type="text" id="serstart" name="serstart" style="text-transform:uppercase" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-3">Serial End: <font color="red">*</font></label>
<div class="col-sm-9">
<input autocomplete="off" class="form-control" type="text" id="serend" name="serend" style="text-transform:uppercase" required>
</div>
</div>
<input type="button" class="btn btn-primary pull-left" id="addrow" value="Add Row" disabled />
<input type="button" class="ibtnDel btn btn-md btn-danger" id="remove" value="Delete Row">
<br>
<table width="100%" class="table order-list table-striped table-bordered table-hover" id="myTable">
<thead>
<tr>
<th class="col-sm-3">
<center />Model
</th>
<th class="col-sm-3">
<center />Code
</th>
<th class="col-sm-3">
<center />Serial Start
</th>
<th class="col-sm-3">
<center />Serial End
</th>
</tr>
</thead>
<tbody id='tbl'>
<tr id="tablerow_0">
<td>
<select name="model[]" id="model0" class="form-control selectpicker show-menu-arrow" data-live-search="true" title="Select your model name" onchange="selectmodel(this)" required>
<?php
$sql = mysqli_query($con,"SELECT model.id,model.model_name,model.code,model.status
FROM model
left join grouped on model.id = grouped.modelandcode
WHERE cat_id='1' and model.status='1' and grouped.status is null
ORDER BY model_name ASC");
$con->next_result();
if(mysqli_num_rows($sql)>0){
while($row=mysqli_fetch_assoc($sql)){
echo "<option value='".$row['id']."'>".$row['model_name']."</option>";
}
} ?>
</select>
</td>
<td>
<input name="code[]" type="text" id="code0" value="" class="form-control" readonly="" />
</td>
<td>
<input type="text" name="serstart[]" id="serstart0" class="form-control" readonly />
</td>
<td>
<input type="text" name="serend[]" id="serend0" class="form-control" onchange="myChangeFunction(this)" required />
</td>
</tr>
</tbody>
</table>
<input type="hidden" value="1" id="start" />
<button id="submit" type="submit" class="btn btn-primary pull-right"><span
class="fa fa-check"> &nbsp Submit</span></button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
<script>
As i said in comment you just need to get index of tr where input has changed and then using that access next tr input and add value there.
Demo Code :
$("[id*=serend]").on("change", function(e) {
var x = $("#serend").val()
if ($(this).val() > (x * 100) / 100) {
alert("You exceed in " + x + " pls do enter below or exact " + x)
} else {
//get index of tr
var row = $(this).closest('tr').index() + 1;
var end = $(this).val(); //get value of input change
end = (parseInt(end) + parseInt(1));
$("tbody tr:eq(" + row + ") td:eq(2) input").val(end) //add inside next input
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table width="100%" class="table order-list table-striped table-bordered table-hover" id="myTable">
<thead>
<tr>
<th class="col-sm-3">
<center />Model
</th>
<th class="col-sm-3">
<center />Code
</th>
<th class="col-sm-3">
<center />Serial Start
</th>
<th class="col-sm-3">
<center />Serial End
</th>
</tr>
</thead>
<tbody id='tbl'>
<tr id="tablerow_0">
<td>
<select name="model[]" id="model0" class="form-control selectpicker show-menu-arrow" data-live-search="true" title="Select your model name" onchange="selectmodel(this)" required>
<option selected disabled> Select your model name</option>
<option value='1'>A</option>
<option value='2'>A2</option>
<option value='3'>A3</option>
</select>
</td>
<td>
<input name="code[]" type="text" id="code0" value="M12" class="form-control" readonly="" />
</td>
<td>
<input type="number" name="serstart[]" id="serstart0" value="1" class="form-control" readonly />
</td>
<td>
<input type="number" name="serend[]" id="serend0" value="11" class="form-control"> </td>
</tr>
<tr id="tablerow_1">
<td>
<select name="model[]" id="model1" class="form-control selectpicker show-menu-arrow" data-live-search="true" title="Select your model name" onchange="selectmodel(this)" required>
<option selected disabled> Select your model name</option>
<option value='1'>A</option>
<option value='2'>A2</option>
<option value='3'>A3</option>
</select>
</td>
<td>
<input name="code[]" type="text" id="code1" value="M12" class="form-control" readonly="" />
</td>
<td>
<input type="number" name="serstart[]" id="serstart1" value="1" class="form-control" readonly />
</td>
<td>
<input type="number" name="serend[]" id="serend1" value="" class="form-control"> </td>
</tr>
<tr id="tablerow_2">
<td>
<select name="model[]" id="model2" class="form-control selectpicker show-menu-arrow" data-live-search="true" title="Select your model name" onchange="selectmodel(this)" required>
<option selected disabled> Select your model name</option>
<option value='1'>A</option>
<option value='2'>A2</option>
<option value='3'>A3</option>
</select>
</td>
<td>
<input name="code[]" type="text" id="code2" value="M12" class="form-control" readonly="" />
</td>
<td>
<input type="number" name="serstart[]" id="serstart2" value="1" class="form-control" readonly />
</td>
<td>
<input type="number" name="serend[]" id="serend2" value="" class="form-control"> </td>
</tr>
</tbody>
</table>

Add two values of different textField to fill another textField on multiple lines

Whenever I input the value of quantity and unit cost for each line, I want to automatically display the multiplied result into the total cost field.
I wrote the jquery script below trying to figure out how to go about it but couldn't get it working
$('.unit, .quantity').on('change', function() {
// var quantity = $('#expenseslist-quantity').val();
// var unit = $('#expenseslist-unit_cost').val();
var total = 0;
$('.quantity, .unit').each(function(){
total = quantity * unit ;
});
$('#expenseslist-total_cost').val(total);
});
Kindly help.
Try to learn how to implement dynamic element
$('.unit, .quantity').on('change', function(event) {
var total1 = 0;
var total2 = 0;
var quantity1 = $('#expenseslist-quantity1').val();
var unit1 = $('#expenseslist-unit_cost1').val();
total1 = quantity1 * unit1 ;
$('#expenseslist-total_cost1').val(total1);
var quantity2 = $('#expenseslist-quantity2').val();
var unit2 = $('#expenseslist-unit_cost2').val();
total2 = quantity2 * unit2 ;
$('#expenseslist-total_cost2').val(total2);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tbody>
<tr class="primary">
<td width="170">
<div class="form-group field-expenseslist-item_id">
<select id="expenseslist-item_id" class="form-control" name="ExpensesList[item_id][]" required="">
<option value="">Select an Item</option>
<option value="1">Vehicle General Repairs And Maintenance</option>
<option value="2">Transportation Cost</option>
</select>
<div class="help-block"></div>
</div>
</td>
<td width="450"><div class="form-group field-expenseslist-request_explanation">
<textarea id="expenseslist-request_explanation" class="form-control" name="ExpensesList[request_explanation][]" rows="2" required=""></textarea>
<div class="help-block"></div>
</div>
</td>
<td width="80"><div class="form-group field-expenseslist-quantity">
<input type="number" id="expenseslist-quantity1" class="form-control quantity" name="ExpensesList[quantity][]" value="0" required="">
<div class="help-block"></div>
</div>
</td>
<td width="130"><div class="form-group field-expenseslist-unit_cost">
<input type="number" id="expenseslist-unit_cost1" class="form-control unit" name="ExpensesList[unit_cost][]" value="0" required="">
<div class="help-block"></div>
</div>
</td>
<td width="150"><div class="form-group field-expenseslist-total_cost">
<input type="text" id="expenseslist-total_cost1" class="form-control total" name="ExpensesList[total_cost][]" value="0" readonly="readonly" required="">
<div class="help-block"></div>
</div>
</td>
<!-- <td>
<button>Add</button>
</td> -->
</tr>
<tr class="primary">
<td width="170">
<div class="form-group field-expenseslist-item_id">
<select id="expenseslist-item_id" class="form-control" name="ExpensesList[item_id][]" required="">
<option value="">Select an Item</option>
<option value="1">Vehicle General Repairs And Maintenance</option>
<option value="2">Transportation Cost</option>
</select>
<div class="help-block"></div>
</div>
</td>
<td width="450"><div class="form-group field-expenseslist-request_explanation">
<textarea id="expenseslist-request_explanation" class="form-control" name="ExpensesList[request_explanation][]" rows="2" required=""></textarea>
<div class="help-block"></div>
</div>
</td>
<td width="80"><div class="form-group field-expenseslist-quantity">
<input type="number" id="expenseslist-quantity2" class="form-control quantity" name="ExpensesList[quantity][]" value="0" required="">
<div class="help-block"></div>
</div>
</td>
<td width="130"><div class="form-group field-expenseslist-unit_cost">
<input type="number" id="expenseslist-unit_cost2" class="form-control unit" name="ExpensesList[unit_cost][]" value="0" required="">
<div class="help-block"></div>
</div>
</td>
<td width="150"><div class="form-group field-expenseslist-total_cost">
<input type="text" id="expenseslist-total_cost2" class="form-control total" name="ExpensesList[total_cost][]" value="0" readonly="readonly" required="">
<div class="help-block"></div>
</div>
</td>
<!-- <td>
<button>Add</button>
</td> -->
<td><div class="btn btn-sm btn-danger rmv">Delete</div></td></tr></tbody>
UPDATED ANSWER:
As per your recent information, I made required changes to the code.
PS: For this, you have to make some changes on your HTML too and have to insert data- attributes on them.
For Unit input: data-type="unit" data-field="field_{1}"
For Quantity input: data-type="qty" data-field="field_{1}"
For the output input area: data-field-count="field_{1}"
After that, try out this code:
$('.unit, .quantity').on('keyup', function() {
let fieldType = $(this).data('type'),
fieldCount = $(this).data('field'),
intOne = $(this).val(),
intTwo = 1
if (fieldType == 'qty') {
intTwo = $('input[data-type=qty]').val()
} else {
intTwo = $('input[data-type=unit]').val()
}
let total = intOne * intTwo
$('input[data-field-count='+ fieldCount +']').val(total);
});
OLD ANSWER:
Since your query is pretty vague, this is what I understood from it:
$('.unit, .quantity').on('keyup', function() {
let qty = $('#expenseslist-quantity').val(),
unit = $('#expenseslist-unit_cost').val()
let total = unit * qty
$('#expenseslist-total_cost').val(total);
});
I don't know why you are using the each loop. Are there more than one unit and quantity fields?

how to calculate the price, subtotal and total based on given value in textbox onkeypress?

I have 4 textboxes, based on the given value I need to calculate everything on keyup functionality. I have used for loop on textboxes and get the value how to calculate on keyup to get the next textbox in loop and append the value in subtotal and total also i have to calculate tax based given quantity and price amount, subtotal, total should be append.
<td width="20%">
<input type="text" onKeyPress="return isNumberKey(event)" class="" name="quan[]" id="quan[]" maxlength="2" autocomplete="off" placeholder="Quantity" >
</td>
<td width="20%">
<input type="text" class="" name="unit[]" id="unit[]" maxlength="5" autocomplete="off" placeholder="Unit" >
</td>
<td width="20%">
<input type="text" class="" name="tax[]" id="tax[]" maxlength="4" autocomplete="off" placeholder="Tax">
</td>
<td width="15%" colspan="1" valign="top">
<input type="text" class="dollar different_amt" name="amt[]" id="amt[]" value="0.00" readonly>
</td>
<div class="col-md-6 col-md-offset-6">
<div class="col-md-7 text-right">
<p>Subtotal</p>
</div>
<div class="col-md-5 text-center">
<input type="text" class="dollar different_amt" readonly>
</div>
<div class="col-md-7 text-right">
<p>Savings to Customer</p>
</div>
<div class="col-md-5 text-center">
<input type="text" class="dollar different_amt" placeholder="Enter Amount...">
</div>
<div class="col-md-7 text-right">
<p><strong>Grand Total</strong></p>
</div>
<div class="col-md-5 text-center">
<input type="text" class="dollar different_amt bald" readonly>
</div>
</div>
var quantity = document.getElementsByName("quan[]");
var unit_level = document.getElementsByName("unit[]");
var tax = document.getElementsByName("tax[]");
for ( var i = 0; i < quantity.length; i++ ){
$(quantity[i]).on("keyup blur",function(){
var get_val_quant = $(this).val();
if($(this).val()==0){
//alert("value should be greater than zero");
document.getElementById('quantity_error').innerHTML="Please enter number greater than zero";
$("#quantity_error").removeClass('field_validation_error hidden');
$("#quantity_error").addClass('field_validation_error');
return false;
} else {
document.getElementById('quantity_error').innerHTML="";
$("#quantity_error").removeClass('field_validation_error');
$("#quantity_error").addClass('field_validation_error hidden');
}
})
//console.log(unit_level[i]);
$(unit_level[i]).on("keyup blur",function(){
var get_unit_price = $(this).val();
if($(this).val()==0){
//alert("value should be greater than zero");
document.getElementById('unit_error').innerHTML="Please enter number greater than zero";
$("#unit_error").removeClass('field_validation_error hidden');
$("#unit_error").addClass('field_validation_error');
return false;
} else if(get_unit_price!=0){
alert((quantity[i]).value());
return false;
} else{
document.getElementById('unit_error').innerHTML="";
$("#unit_error").removeClass('field_validation_error');
$("#unit_error").addClass('field_validation_error hidden');
}
});
$(tax[i]).on("keyup blur",function(){
console.log($(this).val());
});
}
JSFiddle
I have taken 2 static rows with unit,quantity,tax text boxes and last textbox is for total amount for each row. Whenever any changes in any of those 3values it will calculate related price and update in the last textbox And also subtotal,grandtotal with respect to the customer savings value(if any).
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<table>
<tr>
<td width="20%">
<input type="text" class="key-up-event" name="quan[]" id="quan[]" maxlength="2" autocomplete="off" placeholder="Quantity" >
</td>
<td width="20%">
<input type="text" class="key-up-event" name="unit[]" id="unit[]" maxlength="5" autocomplete="off" placeholder="Unit" >
</td>
<td width="20%">
<input type="text" class="key-up-event" name="tax[]" id="tax[]" maxlength="4" autocomplete="off" placeholder="Tax">
</td>
<td width="15%" colspan="1" valign="top">
<input type="text" class="dollar different_amt" name="amt[]" id="amt[]" value="0.00" readonly>
</td>
</tr>
<tr>
<td width="20%">
<input type="text" class="key-up-event" name="quan[]" id="quan[]" maxlength="2" autocomplete="off" placeholder="Quantity" >
</td>
<td width="20%">
<input type="text" class="key-up-event" name="unit[]" id="unit[]" maxlength="5" autocomplete="off" placeholder="Unit" >
</td>
<td width="20%">
<input type="text" class="key-up-event" name="tax[]" id="tax[]" maxlength="4" autocomplete="off" placeholder="Tax">
</td>
<td width="15%" colspan="1" valign="top">
<input type="text" class="dollar different_amt" name="amt[]" id="amt[]" value="0.00" readonly>
</td>
</tr>
</table>
<div class="col-md-6 col-md-offset-6">
<div class="col-md-7 text-right">
<p>Subtotal</p>
</div>
<div class="col-md-5 text-center">
<input type="text" class="dollar different_amt" id="subttot" readonly>
</div>
<div class="col-md-7 text-right">
<p>Savings to Customer</p>
</div>
<div class="col-md-5 text-center">
<input type="text" class="dollar different_amt" id="savngs" placeholder="Enter Amount...">
</div>
<div class="col-md-7 text-right">
<p><strong>Grand Total</strong></p>
</div>
<div class="col-md-5 text-center">
<input type="text" class="dollar different_amt bald" id="fintot" readonly>
</div>
</div>
<script type="text/javascript">
$(".key-up-event").on("keyup blur", function(){
if ($(this).attr("name") == "quan[]") {
var ind = $("input[name='quan[]']").index(this);
} else if ($(this).attr("name") == "unit[]") {
var ind = $("input[name='unit[]']").index(this);
} else if ($(this).attr("name") == "tax[]") {
var ind = $("input[name='tax[]']").index(this);
}
var quan, unit, tax, amt;
quan = parseFloat($("input[name='quan[]']:eq("+ind+")").val());
quan = (isNaN(quan)) ? 0 : quan;
unit = parseFloat($("input[name='unit[]']:eq("+ind+")").val());
unit = (isNaN(unit)) ? 0 : unit;
tax = parseFloat($("input[name='tax[]']:eq("+ind+")").val());
tax = (isNaN(tax)) ? 0 : tax;
amt = quan*unit + tax;
$("input[name='amt[]']:eq("+ind+")").val(amt)
subtotal();
});
function subtotal() {
var tot = 0;
$("input[name='amt[]']").each(function(){
tot += parseFloat($(this).val());
});
$("#subttot").val(tot)
finaltotal();
}
$("#savngs").on("keyup blur", function(){
finaltotal();
});
function finaltotal() {
var tot = 0;
var subtot = parseFloat($("#subttot").val());
subtot = (isNaN(subtot)) ? 0 : subtot;
var savngs = parseFloat($("#savngs").val());
savngs = (isNaN(savngs)) ? 0 : savngs;
tot = subtot-savngs;
$("#fintot").val(tot)
}
</script>

Categories

Resources