I have a calculation table and the total becomes NaN after adding 10 rows.
I have even tried the suggestions as stated within this Stackoverflow article.
I have been testing this for over a day now and cannot fix the error. What am I missing?
jQuery(document).ready(function($){
var counter = 2;
$("#addItem").click(function () {
if(counter>50){
alert("You have reached the maximum items allowed (50)!");
return false;
}
var newTextBoxDiv = $(document.createElement('tr'))
.attr("id", 'itemRow' + counter);
newTextBoxDiv.after().html('<td class="first"><input placeholder="Charge # ' + counter + '" class="chrg" type="text" name="data[' + counter + '][0]" id="chrg' + counter + '" ></td>' + '<td><input placeholder="Item/Part # ' + counter + '" class="item" type="text" name="data[' + counter + '][1]" id="item' + counter + '" ></td>' + '<td><input placeholder="Description ' + counter + '" class="desc" type="text" name="data[' + counter + '][2]" id="desc' + counter + '" ></td>' + '<td style="text-align:center;"><input placeholder="Qty ' + counter + '" class="qty" type="text" name="data[' + counter + '][3]" id="qty' + counter + '" size="5" style="text-align:center;" /></td>' + '<td style="text-align:right;"><input placeholder="Cost ' + counter + '" class="cost" type="text" name="data[' + counter + '][4]" id="cost' + counter + '" size="10" style="text-align:right;" /></td>' + '<td style="text-align:right;"><span class="input-group-addon">$</span><input placeholder="Sub-Total ' + counter + '" class="stotal" type="text" name="stotal'+ counter + '" id="stotal'+ counter +'" size="10" style="text-align:right;" readonly /></td>');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$(document).on('keyup', '.cost', function(st){
// grab ID to get row number
thisID = $(this).attr("id");
rowNum = thisID.slice(-1);
//get Amount entered
qty = $('#qty'+rowNum).val();
//get QTY
cost = $('#cost'+rowNum).val();
$('#stotal'+rowNum).val((qty*cost).toFixed(2));
currentCount = counter-1;
var tot = Math.round(0);
$('.stotal').each(function() {
tot += parseFloat($(this).val());
});
$('#preTotal').val((tot).toFixed(2));
$('#grand_total').val((tot).toFixed(2));
});
//calculate preTotal
$(document).on('focusin', '#shipping', function(pt){
var selection = document.getElementById("addShip");
if (selection.checked){
$("#shipping").change(function(preTotal,shipping) { // input on change
var preTotal = document.getElementById('preTotal').value;
var shipping = document.getElementById('shipping').value || 0;
var pTotal = parseFloat(shipping) + parseFloat(preTotal);
document.getElementById('preTotal').value = (pTotal.toFixed(2));
});
} else {
var preTotal = document.getElementById('preTotal').value;
var shipping = document.getElementById('shipping').value || 0;
var sTotal = parseFloat(preTotal);
document.getElementById('preTotal').value = (sTotal.toFixed(2));
}
});
//calculate taxes and total
$(document).on('focusin', '#taxTotal', function(tt){
var selection = document.getElementById("addShip");
//get field results
var preTotal = document.getElementById('preTotal').value || 0;
var shipping = document.getElementById('shipping').value || 0;
var taxTotal = document.getElementById('taxTotal').value || 0;
var taxRate = document.getElementById('taxRate').value || 0;
var gTotal = document.getElementById('grand_total').value || 0;
$("#taxTotal").change(function() { // input on change
var tTotal = document.getElementById('taxTotal').value / document.getElementById('preTotal').value * 100;
document.getElementById('taxRate').value = (tTotal.toFixed(2));
});
});
//calculate total + taxes
$(document).on('focusout', '#taxTotal', function(gt){
var shipping = document.getElementById('shipping').value || 0;
var tTotal = document.getElementById('taxTotal').value || 0;
var gTotal = document.getElementById('grand_total').value;
var fTotal = parseFloat(shipping) + parseFloat(tTotal) + parseFloat(gTotal);
document.getElementById('grand_total').value = (fTotal.toFixed(2));
});
});
}
function focusField() {
$('#addItem').click(function(){
$('.chrg').focus();
});
th {padding: 2px 2px;}
td {padding: 2px 2px;}
input {padding: 0px 2px;}
#addItemBtn {}
input.filler {border-color:#fff;border-style:solid;}
.input-group-addon {
padding: 2px 5px;
font-size: 14px;
font-weight: 400;
line-height: 1;
color: #555;
text-align: center;
background-color: #eee;
box-shadow: inset 0 0 0 1px grey;
border-right: 1px #eee solid;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="TextBoxesGroup" style="width:100%;">
<tr>
<th style="text-align:left;">Charge #</th>
<th style="text-align:left;">Item/Part #</th>
<th style="text-align:left;">Description</th>
<th style="text-align:center;">Qty</th>
<th style="text-align:right;">Cost</th>
<th style="text-align:right;">Sub-total</th>
</tr>
<tr id="itemRow1">
<td><input placeholder="Charge # 1" class="chrg" type="text" id="chrg1" autofocus /></td>
<td><input placeholder="Item/Part # 1" class="item" type="text" id="item1" style="margin-bottom:0 !important" /></td>
<td><input placeholder="Description 1" class="desc" type="text" id="desc1" /></td>
<td style="text-align:center;"><input placeholder="Qty 1" class="qty" type="text" id="qty1" size="5" style="text-align:center;" /></td>
<td style="text-align:right;"><input placeholder="Cost 1" class="cost" type="text" id="cost1" size="10" style="text-align:right;" /></td>
<td style="text-align:right;"><span class="input-group-addon">$</span><input placeholder="Sub-Total 1" class="stotal" type="text" id="stotal1" size="10" style="text-align:right;" readonly /></td>
</tr>
</table>
<table style="width:100%;">
<tr id="rowFiller">
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td><input class="btn btn-primary" type="button" id="addItem" value="Add Item" size="10" style="float:right;" onclick="focusField()" /></td>
</tr>
<!--<tr id="addItemBtn">
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td><input type="button" id="addItem" value="Add Item" style="float:right;" /></td>
</tr>-->
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td style="text-align:right;">
<label style="padding-right:5px;">remove shipping from taxable total
<input type="checkbox" id="addShip" class="addShip" name="addShip" checked ></label>
</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td style="text-align:right;">
<label style="font-weight:bold;padding-right:5px;display:inline-block;">Shipping</label>
<span class="input-group-addon">$</span>
<input placeholder="$00.00" name="shipping" id="shipping" size="10" style="float:right;text-align:right;" />
</td>
</tr>
<tr>
<td></td>
<td></td>
<td style="text-align:right;">
<label style="font-weight:bold;padding-right:5px;display:inline-block;">Pre-Total</label>
<input name="preTotal" id="preTotal" size="10" style="float:right;text-align:right;" readonly /></td>
<td></td>
<td>
</td>
<td style="text-align:right;">
<div style="text-align:right;display:inline;border-right:1px #ccc solid;margin-right:5px;">
<label style="font-weight:bold;padding-right:5px;display:inline-block;">Tax</label>
<input placeholder="00" class="taxRate" name="taxRate" id="taxRate" size="1" style="text-align:center;" />
<label style="font-weight:bold;display:inline-block;">%</label>
</div>
<label style="font-weight:bold;padding-right:5px;display:inline-block;">Total Tax</label>
<span class="input-group-addon">$</span><input placeholder="$00.00" name="taxTotal" id="taxTotal" size="10" style="float:right;text-align:right;" />
</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td style="text-align:right;font-weight:bold;"><label style="font-weight:bold;padding-right:5px;display:inline-block;">Grand Total</label>
<span class="input-group-addon">$</span><input placeholder="$00.00" name="grand_total" id="grand_total" size="10" style="float:right;text-align:right;" readonly /></td>
</tr>
</table>
Update:
I have resolved the issue as shown in the jsfiddle provided.
Add below condition to your code before actually parsing the values to float.
if(preTotal === ""){
preTotal = 0; // assign number value you like
}
and
if(gTotal === ""){
gTotal = 0; // here also.
}
Because, for the first time, these values come as empty strings.
Also, I noticed the "focusin" event being handled here. It fires the handler everytime user goes to put something inside the test box provided.
Related
I've a simple form to auto calculate amount entered in the Amount field.
The Total Sum field is only updated upon entering the first row's Amount field. Total Sum field is not updated for subsequent rows.`
<?php
$sno = 1;
?>
<html>
<head>
<style>
body {
font-family: sans-serif;
}
#summation {
font-size: 18px;
font-weight: bold;
color: #174C68;
}
.amt {
background-color: #FEFFB0;
//font-weight: bold;
text-align: right;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<table class="table table-bordered table-hover" id="tab_logic">
<thead>
<tr>
<th />
<th>Invoice No.</th>
<th>Invoice Date</th>
<th>Description</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<tr id='addr0'>
<td>
<?php echo $sno;?>
</td>
<td width="40px"><input class="txt" type="text" name="invoiceNo" style="text-transform:uppercase" /></td>
<td><input type="date" name="date" /></td>
<td><input class="txt" type="text" name="txt" /></td>
<td><input class="amt" type="number" name="amt" min="0" step="0.01" /></td>
</tr>
<tr id='addr1'></tr>
</tbody>
</table>
</div>
</div>
<button id="add_row" class="btn btn-primary btn-lg pull-left">Add Row</button>
<table>
<tr id="summation">
<td align="right" colspan="3">Total Sum :</td>
<td align="right" colspan="2"><span id="sum">0</span></td>
</tr>
</table>
</div>
<script>
$(document).ready(function() {
var i = 1;
var j = 1;
$("#add_row").click(function() {
$('#addr' + i).html("<td>" + (i + 1) + "</td><td><input type='text' name='invoiceNo" + i + "' class='form-control input-md' style='text-transform:uppercase'/></td><td><input type='date' name='date" + i + "' class='form-control input-md'/></td><td><input type='text' name='text" + i + "' class='form-control input-md'/></td><td><input type='number' name='amt" + i + "' class='amt' min='0' step='0.01'/></td>");
$('#tab_logic').append('<tr id="addr' + (i + 1) + '"></tr>');
i++;
});
$('.amt').each(function() {
$(this).keyup(function() {
calculateSum();
});
});
$('.amt' + j).each(function() {
$(this).keyup(function() {
calculateSum();
});
j++;
});
});
function calculateSum() {
var sum = 0;
$(".amt").each(function() {
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
}
});
$("#sum").html(sum.toFixed(2));
}
</script>
</body>
</html>
The Total Sum field for subsequent rows is updated only when I change the contents in 1st row's Amount field.
How can I update the Total Sum automatically whenever the Amount field is entered for subsequent rows?
Thank you.
*** Updates ***
I've updated my code as per Paul's suggestion.
<?php
$sno = 1;
$i = 0;
?>
<html>
<head>
<style>
body {
font-family: sans-serif;
}
#summation {
font-size: 18px;
font-weight: bold;
color: #174C68;
}
.amt {
//background-color: #FEFFB0;
//font-weight: bold;
text-align: right;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<form enctype="multipart/form-data" method="post" name="form" id="form" action="data.php">
<body>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<table class="table table-bordered table-hover" id="tab_logic" border="1" style="border:2px solid black;border-collapse:collapse">
<thead>
<tr>
<th />
<th>Invoice No.</th>
<th>Invoice Date</th>
<th>Description</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<tr id='addr0'>
<td>
<?php echo $sno;?>
</td>
<td width="40px"><input class="txt" type="text" name="invoiceNo[<?php echo $i; ?>][invoiceNo]" style="text-transform:uppercase" /></td>
<td><input type="date" name="date[<?php echo $i; ?>][date]" /></td>
<td><input class="txt" type="text" name="desc[<?php echo $i; ?>][desc]" /></td>
<td><input class="amt" type="number" name="amt[<?php echo $i; ?>][amt]" step="0.01" /></td>
</tr>
<tr id='addr1'></tr>
</tbody>
</table>
</div>
</div>
<br>
<button id="add_row" class="btn btn-primary btn-lg pull-left" type="button">Add Row</button>
<table>
<tr id="summation">
<td align="right" colspan="3">Total Sum :</td>
<td align="right" colspan="2"><span id="sum">0.00</span></td>
</tr>
</table>
</div>
<br>
<tr>
<!--<td align="center"><button type="button" id="btn-ser1">Submit</button></td>-->
<td align="center"><button type="submit" id="btn-ser1">Submit</button></td>
</tr>
<script>
$(document).ready(function() {
var i = 1;
$('#add_row').click(function() {
$('#addr' + i).html("<td>" + (i + 1) + "</td><td><input type='text' name='invoiceNo[" + i + "][invoiceNo]' class='form-control input-md' style='text-transform:uppercase'/></td><td><input type='date' name='date[" + i + "][date]' class='form-control input-md'/></td><td><input type='text' name='desc[" + i + "][desc]' class='form-control input-md'/></td><td><input type='number' name='amt[" + i + "][amt]' class='amt' min='0' step='0.01'/></td>");
$('#tab_logic').append('<tr id="addr' + (i + 1) + '"></tr>');
i++;
});
});
$('#tab_logic').on('change', '.amt', function() {
this.value = parseFloat(this.value).toFixed(2);
});
// Use an event delegate on amt
$('#tab_logic').on('change', '.amt', function() {
calculateSum();
});
function calculateSum() {
var sum = 0;
$('.amt').each(function() {
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
}
});
$('#sum').html(sum.toFixed(2));
$('#total').val(sum);
}
//$('#btn-ser1').click(function(){
// data_array = $('#form').serialize();
// alert(data_array);
$('form').submit(function() {
data_array = $('#form').serialize();
//alert(data_array);
$('#arr').val(data_array);
});
</script>
<!--<input type="hidden" name="sno" value="<?php echo $sno; ?>">-->
<input type="hidden" id="total" name="total" />
<input type="hidden" id="arr" name="arr" />
</body>
</html>
When I submit the form & print the array, I get this sample output:
invoiceNo[0][invoiceNo]=a1&date[0][date]=2021-02-18&desc[0][desc]=a1&amt[0][amt]=1.47&invoiceNo[1][invoiceNo]=b2&date[1][date]=2021-02-17&desc[1][desc]=b2&amt[1][amt]=2.58&invoiceNo[2][invoiceNo]=c3&date[2][date]=2021-02-16&desc[2][desc]=c3&amt[2][amt]=3.69&total=7.74&arr=
How can I get the recurring values of invoiceNo, date, desc & amt to insert into a SQL statement?
Don't need any of the keyup, you can use the amt to delegate the handling to any of those.
Basically, remove this handling:
$('.amt').each(function() {
$(this).keyup(function() {
calculateSum();
});
});
$('.amt' + j).each(function() {
$(this).keyup(function() {
calculateSum();
});
j++;
});
Replace with:
// Use a change event delegate on amt
$('#tab_logic').on('change', '.amt', function() {
calculateSum();
});
Try the runnable example below.
Click the spinner buttons, the sum change is immediate. If a value is typed in, the sum updates after the field loses focus.
<?php
$sno = 1;
?>
<html>
<head>
<style>
body {
font-family: sans-serif;
}
#summation {
font-size: 18px;
font-weight: bold;
color: #174C68;
}
.amt {
background-color: #FEFFB0;
//font-weight: bold;
text-align: right;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<table class="table table-bordered table-hover" id="tab_logic">
<thead>
<tr>
<th />
<th>Invoice No.</th>
<th>Invoice Date</th>
<th>Description</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<tr id='addr0'>
<td>
<?php echo $sno;?>
</td>
<td width="40px"><input class="txt" type="text" name="invoiceNo" style="text-transform:uppercase" /></td>
<td><input type="date" name="date" /></td>
<td><input class="txt" type="text" name="txt" /></td>
<td><input class="amt" type="number" name="amt" min="0" step="0.01" /></td>
</tr>
<tr id='addr1'></tr>
</tbody>
</table>
</div>
</div>
<button id="add_row" class="btn btn-primary btn-lg pull-left">Add Row</button>
<table>
<tr id="summation">
<td align="right" colspan="3">Total Sum :</td>
<td align="right" colspan="2"><span id="sum">0</span></td>
</tr>
</table>
</div>
<script>
$(document).ready(function() {
var i = 1;
var j = 1;
$("#add_row").click(function() {
$('#addr' + i).html("<td>" + (i + 1) + "</td><td><input type='text' name='invoiceNo" + i + "' class='form-control input-md' style='text-transform:uppercase'/></td><td><input type='date' name='date" + i + "' class='form-control input-md'/></td><td><input type='text' name='text" + i + "' class='form-control input-md'/></td><td><input type='number' name='amt" + i + "' class='amt' min='0' step='0.01'/></td>");
$('#tab_logic').append('<tr id="addr' + (i + 1) + '"></tr>');
i++;
});
});
// Use an event delegate on amt
$('#tab_logic').on('change', '.amt', function() {
calculateSum();
});
function calculateSum() {
var sum = 0;
$(".amt").each(function() {
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
}
});
$("#sum").html(sum.toFixed(2));
}
</script>
</body>
</html>
Can someone here help me with this? The problem with this code is that when you add column(add supplier) it can't get the grand total for each total column. Does anyone here know how to solve this? It will be a big help with my project. Thanks in advance. This is my javascript that calculates the total (not the grand total)
$(function() {
$('#add_supplier').click(function() {
$('#supplier_table > thead > tr#first-header').append('<th colspan="2" class="supplier_name">Supplier</th>');
$('#supplier_table > thead > tr#second-header').append(
'<th>Price</th>' +
'<th>Total</th>'
);
$('#supplier_table > tbody > tr').append(
'<td><input type="text" class="form-control price text-right" ></td>' +
'<td><input type="text" class="form-control total text-right" readonly></td>'
);
$('#grandtotal > tbody > tr').append(
'<td><input class="form-control" disabled></td>' +
'<td><input type="text" class="form-control grandtotal text-right" readonly=""></td>'
);
refresh_index();
});
$('#add_item').click(function() {
$('#supplier_table tbody').append($("#supplier_table tbody tr:last").clone());
refresh_index();
});
function refresh_index() {
$('.price').each(function(i) {
i++;
$(this).attr('id', 'price-' + i);
$(this).attr('data-num', i);
event_handler();
});
$('.total').each(function(i) {
i++;
$(this).attr('id', 'total-' + i);
});
$('.qty').each(function(i) {
i++;
$(this).attr('id', 'qty-' + i);
});
$('.grandtotal').each(function(i) {
i++;
$(this).attr('id', 'grandtotal-' + i);
});
$('.supplier_name').each(function(i) {
i++;
$(this).attr('id', 'supplier_name-' + i);
});
}
refresh_index();
function event_handler() {
$('.price').unbind('keyup').bind('keyup', function() {
var id = this.id;
var num = id.split('-');
var pos = $(this).closest('tr').index() + 1;
var qty = $('#qty-' + pos).val();
var price = $(this).val();
var total = parseFloat(qty) * parseFloat(price);
if (isNaN(total)) {
var total = 0;
}
$('#total-' + num[1]).val(total);
var num_of_supplier_name = $('.supplier_name').length;
sum_of_total(num_of_supplier_name);
});
}
function sum_of_total(num) {
var sum = 0;
//iterate through each textboxes and add the values
$(".total").each(function() {
//add only if the value is number
if (!isNaN($(this).val()) && $(this).val().length != 0) {
sum += parseFloat(this.value);
}
});
//.toFixed() method will roundoff the final sum to 2 decimal places
$("#grandtotal-" + num).val(sum);
}
});
#supplier_table thead th,
td {
text-align: center;
}
#grandtotal tbody input:disabled {
border: none;
border-color: transparent;
background-color: transparent;
outline: none;
box-shadow: inset 0px 0px 0px 0px red;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="container">
<h2>Bordered Table</h2>
<p>The .table-bordered class adds borders to a table:</p>
<button type="button" class="btn btn-default" id="add_supplier">Add Supplier</button>
<button type="button" class="btn btn-default" id="add_item">Add Item</button>
<table class="table table-bordered" id="supplier_table">
<thead>
<tr id="first-header">
<th></th>
<th></th>
<th colspan="2" class="supplier_name" id="supplier_name-1">Supplier</th>
</tr>
<tr id="second-header">
<th>Item</th>
<th>Qty</th>
<th>Price</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr class="tbody-tr">
<td><input type="text" class="form-control" value="Mouse" readonly=""></td>
<td><input type="text" class="form-control qty" value="10" readonly=""></td>
<td><input type="text" class="form-control price"></td>
<td><input type="text" class="form-control total for_sum-1" readonly=""></td>
</tr>
<tr class="tbody-tr">
<td><input type="text" class="form-control" value="Keyboard" readonly=""></td>
<td><input type="text" class="form-control qty" value="20" readonly=""></td>
<td><input type="text" class="form-control price"></td>
<td><input type="text" class="form-control total for_sum-1" readonly=""></td>
</tr>
<tr class="tbody-tr">
<td><input type="text" class="form-control" value="Monitor" readonly=""></td>
<td><input type="text" class="form-control qty" value="30" readonly=""></td>
<td><input type="text" class="form-control price"></td>
<td><input type="text" class="form-control total for_sum-1" readonly=""></td>
</tr>
</tbody>
<table class="table table-bordered" id="grandtotal">
<thead>
<tr>
</tr>
</thead>
<tbody>
<tr>
<td><input class="form-control" disabled=""></td>
<td><input class="form-control" disabled=""></td>
<td><input class="form-control" disabled value="Grand Total : " style="text-align: right;"></td>
<td><input type="text" class="form-control grandtotal text-right" readonly=""></td>
</tr>
</tbody>
</table>
</table>
</div>
Demo jsFiddle
The reason is an easy mistake often made in jQuery.
Your code is interpreted at first page load, all subsequent changes in the DOM are ignored.
There is an easy trick to always interpret all .totals.
Make "body" to find all "totals".
function sum_of_total(num) {
var sum = 0;
//iterate through each textboxes and add the values
$("body").find(".total").each(function() {
//add only if the value is number
if (!isNaN($(this).val()) && $(this).val().length != 0) {
sum += parseFloat(this.value);
}
});
//.toFixed() method will roundoff the final sum to 2 decimal places
$("#grandtotal-" + num).val(sum);
}
working fiddle: https://jsfiddle.net/juf54wby/
using this code i can already calculate two value in row now I am trying to sum column values below local column field all column value with this,
<table class="table order-list turf" id="turf">
<tr>
<td>Items</td>
<td>Local</td>
<td>Foreign</td>
<td>Total</td>
</tr>
<tr>
<td class="col-sm-3"><input type="text" name="" value="item1"></td>
<td class="col-sm-3 calculated_value">
<input type="text" name="value1[]" class="calculated_value"/></td>
<td class="col-sm-3 calculated_value">
<input type="text" name="value2[]" class="form-control calculated_value" />
</td>
<td class="col-sm-3 total">
<input type="text" name="total[]" class="form-control total" id="total" readonly="" />
</td>
<td class="col-sm-2"><a class="deleteRow"></a>
<input type="button" class="btn btn-sm btn-success " id="addrow" value="Add" />
</td>
</tr>
<tr class="grand-total persist">
<td>Total Investment</td>
<td id="local_total"><input type="text" readonly="" name=""></td>
<td id="foreign_total"><input type="text" readonly="" name=""></td>
<td id="total_total"><input type="text" readonly="" name=""></td>
</tr>
</table>
var counter = 1;
$("body").on("input", ".calculated_value", function() {
var parent_row = $(this).closest('tr');
var totalincome = 0;
parent_row.find('.calculated_value').each(function() {
totalincome += parseInt($(this).val() || 0);
});
parent_row.find(".total").val(totalincome);
Demo
I hope this is what you need. Code could be refactored but I think you can do it yourself.
$(document).ready(function() {
var counter = 1;
$("body").on("input", ".calculated_value", function() {
calculate(this);
});
function calculate(elm) {
var parent_row = $(elm).closest('tr');
var elTotalIncome = $("#local_milion_grand_total").find("input");
var elTotalForeign = $("#foreign_milion_grand_total").find("input");
var elTotal = $('#total_milion_grand_total').find("input");
var totalincome = 0;
var totalLocal = 0;
var totalForeign = 0;
var total = 0;
parent_row.find('.calculated_value').each(function() {
totalincome += parseInt($(this).val() || 0);
});
parent_row.find('.total').val(totalincome);
for (i = 0; i < $("tbody tr").length; i++) {
let elCol = $($("tbody tr")[i]).find("td input");
let tmp = parseInt(elCol[1].value);
let tmp2 = parseInt(elCol[2].value);
let tmp3 = parseInt(elCol[3].value);
if (isNaN(tmp)) tmp = 0;
if (isNaN(tmp2)) tmp2 = 0;
if (isNaN(tmp3)) tmp3 = 0;
totalLocal += tmp;
totalForeign += tmp2;
total += tmp3;
}
elTotal.val(total);
elTotalIncome.val(totalLocal);
elTotalForeign.val(totalForeign);
}
//add new row button
$("#addrow").on("click", function() {
var newRow = $("<tr>");
var cols = "";
cols += '<td><input type="text" value="Item ' + counter + '"></td>';
cols += '<td><input type="text" class="form-control calculated_value" name="value1[]"></td>';
cols += '<td><input type="text" class="form-control calculated_value" name="foreign_milion[]"></td>';
cols += '<td><input type="text" class="form-control total" name="total_milion[]" readonly></td>';
cols += '<td><input type="button" class="ibtnDel btn btn-md btn-danger " value="Delete"></td>';
newRow.append(cols);
$("table.order-list").append(newRow);
counter++;
});
$("table.order-list").on("click", ".ibtnDel", function(event) {
if (counter == 1) return;
$(this).closest("tr").remove();
counter -= 1
calculate(this);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table class="table order-list turf" id="turf">
<thead>
<tr>
<td>Items</td>
<td>Local(Milion Taka/Milion US$)</td>
<td>Foreign(Milion Taka/Milion US$)</td>
<td>Total(Milion Taka/Milion US$)</td>
<td> <input type="button" class="btn btn-sm btn-success " id="addrow" value="Add" /></td>
</tr>
</thead>
<tbody>
<tr>
<td class="col-sm-3">
<input type="text" name="" value="item1">
</td>
<td class="col-sm-3 calculated_value">
<input type="text" name="value1[]" class="form-control calculated_value_row calculated_value" />
</td>
<td class="col-sm-3 calculated_value">
<input type="text" name="value2[]" class="form-control calculated_value_row calculated_value" />
</td>
<td class="col-sm-3 total">
<input type="text" name="total[]" class="form-control total" id="total" readonly="" />
</td>
<td><input type="button" class="ibtnDel btn btn-md btn-danger " value="Delete"></td>
</tr>
</tbody>
<tfoot>
<tr class="grand-total persist">
<td>Total Investment</td>
<td id="local_milion_grand_total"><input type="text" class="form-control local_milion_grand_total" readonly="" name=""></td>
<td id="foreign_milion_grand_total"><input type="text" class="form-control" readonly="" name=""></td>
<td id="total_milion_grand_total"><input type="text" class="form-control" readonly="" name=""></td>
</tr>
</tfoot>
</table>
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Add Data Dynamically in the table and Edit then checkbox value is not updating this is problem.
Here in jsFiddle
Code Here in JSFiddle
Please review working snippet.
var cnt = 0;
var count = 1;
function BindData(count) {
$("#s_name").val($("#name_" + count).html());
$("#product_names").val($("#pro_" + count).html());
$("#emailid").val($("#email_" + count).html());
$("#mobileno").val($("#mobi_" + count).html());
$('input[name="are"]:checked').val($("#ur_" + count).html());
$("#price").val($("#pric_" + count).html());
$("#t_pro").val($("#totalPro_" + count).html());
$("#total_price").val($("#totalPri_" + count).html());
var checkedHTML = $("#productWith_" + count).html();
var arrCheckedValues = checkedHTML.split(",");
$('.ads_Checkbox').each(function() {
var values = $(this).val();
if (arrCheckedValues.indexOf(values) > -1) {
$(this).prop("checked", true);
}
});
$("#order").attr("value", "Update Order");
$("#order").attr("onclick", "EditData(" + count + ")");
}
function EditData(count) {
$("#name_" + count).html($("#s_name").val());
$("#pro_" + count).html($("#product_names").val());
$("#email_" + count).html($("#emailid").val());
$("#mobi_" + count).html($("#mobileno").val());
$("#ur_" + count).html($('input[name="are"]:checked').val());
$("#pric_" + count).html($("#price").val());
$("#totalPro_" + count).html($("#t_pro").val());
$("#totalPri_" + count).html($("#total_price").val());
var chk = '';
var arrCheckedValues = [];
$('.ads_Checkbox:checked').each(function() {
var values = $(this).val();
arrCheckedValues.push(values);
});
chk = arrCheckedValues.join(",");
$("#productWith_" + count).html(chk);
$("#order").attr("value", "Order");
$("#order").attr("onclick", "AddData()");
//AddData(); /// ADD NEW DATA
$("#s_name").val("");
//$("#product_names").val("");
$("#emailid").val("");
$("#mobileno").val("");
//$('input[name="are"]').prop("");
$("#price").val("");
$("#t_pro").val("");
$("#total_price").val("");
// Clear all CheckBoxes
$('input[type=checkbox]').each(function() {
this.checked = false;
});
}
function AddData() {
var shop_name = $("#s_name").val();
var pro_name = $("#product_names").val();
var email = $("#emailid").val();
var mobi = $("#mobileno").val();
var ur = $('input[name="are"]:checked').val();
var pric = $("#price").val();
var total_pro = $("#t_pro").val();
var total_pri = $("#total_price").val();
var chk = '';
var arrCheckedValues = [];
$('.ads_Checkbox:checked').each(function() {
var values = $(this).val();
arrCheckedValues.push(values);
//chk += values;
});
chk = arrCheckedValues.join(",");
$("#mytab").append('<tr><td id="name_' + count + '">' + shop_name + '</td><td id="pro_' + count + '">' + pro_name +
'</td><td id="email_' + count + '">' + email + '</td><td id="mobi_' + count + '">' + mobi +
'</td><td id="ur_' + count + '">' + ur + '</td><td id="pric_' + count + '">' + pric + '</td><td id="totalPro_' + count + '">' + total_pro + '</td><td id="totalPri_' + count + '">' + total_pri + '</td><td id="productWith_' + count + '">' + chk + '</td><td><button type="button" class="delete">Delete</button></td><td><button type="button" id="edit" onclick="BindData(' + count + ');" >Edit</button></td></tr>');
cnt++;
count++;
$("#s_name").val("");
//$("#product_names").val("");
$("#emailid").val("");
$("#mobileno").val("");
//$('input[name="are"]').val("");
$("#price").val("");
$("#t_pro").val("");
$("#total_price").val("");
// Clear all CheckBoxes
$(".ads_Checkbox").prop("checked", false);
/*$('input[type=checkbox]').each(function()
{
this.checked = false;
});*/
if (cnt > 0) {
$("#dummy").hide();
}
}
$(document).ready(function() {
$("#price,#t_pro").blur(function() {
$('#total_price').val($('#price').val() * $('#t_pro').val());
});
$(document).on('click', '.delete', function() {
//When delete the record then clear all checkboxes
$('input[type=checkbox]').each(function() {
this.checked = false;
});
var par = $(this).parent().parent(); //tr
par.remove();
cnt--;
if (cnt == 0) {
$("#dummy").show();
}
});
});
* {
font-family: arial;
font-size: 13px;
}
.align-center {
text-align: center;
}
input.txt {
color: #00008B;
background-color: #E3F2F7;
border: 1px inset #00008B;
width: 200px;
}
input.btn {
color: #00008B;
background-color: #ADD8E6;
border: 1px outset #00008B;
}
form div {
clear: left;
margin: 0;
padding: 0;
padding-top: 0.9em;
}
form div label {
float: left;
width: 20%;
font: bold 0.9em Arial, Helvetica, sans-serif;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<table cellpadding="2" width="50%" align="center" cellspacing="2" id="myTable">
<tr>
<td colspan=2>
<center>
<font size=4>
<b>Product Detail Form</b>
</font>
</center>
</td>
</tr>
<tr>
<td>
<label for="s_name">Shop Name</label>
</td>
<td>
<input type="text" id="s_name" size="30" class="txt">
</td>
</tr>
<tr>
<td>
<label for="product_names">Product Name</label>
</td>
<td>
<select id="product_names" class="product_name">
<option value="-1" selected>select..</option>
<option value="pc">PC</option>
<option value="laptop">Laptop</option>
<option value="mobile_phone">Mobile Phone</option>
<option value="plasma_screen">Plasma Screen</option>
</select>
</td>
</tr>
<tr>
<td>
<label for="emailid">EmailId</label>
</td>
<td>
<input type="text" id="emailid" size="30" class="txt">
</td>
</tr>
<tr>
<td>
<label for="mobileno">MobileNo</label>
</td>
<td>
<input type="text" id="mobileno" size="30" class="txt">
</td>
</tr>
<tr>
<td>
<label for="r1">What You Are</td>
<td>
<input type="radio" name="are" value="Buyer" id="r1" size="10" checked>
<label for="r1">Buyer</label>
<input type="radio" name="are" value="Seller" id="r2" size="10">
<label for="r2">Seller</label>
</td>
</tr>
<tr>
<td>
<label for="price">Price</label>
</td>
<td>
<input type="text" id="price" size="30" class="txt">
</td>
</tr>
<tr>
<td>
<label for="t_pro">Total Product</label>
</td>
<td>
<input type="text" id="t_pro" size="30" class="txt">
</td>
</tr>
<tr>
<td>
<label for="total_price">Total Price</label>
</td>
<td>
<input type="text" id="total_price" size="30" class="txt">
</td>
</tr>
<tr>
<td>
<label for="1">Product With:</td>
<td>
<input type="checkbox" name="chk1" id="chk1" class="ads_Checkbox" value="Box">Box
<br>
<input type="checkbox" name="chk2" id="chk2" class="ads_Checkbox" value="Bill">Bill
<br>
<input type="checkbox" name="chk3" id="chk3" class="ads_Checkbox" value="Bill-BOx">Bill-BOx
<br>
<input type="checkbox" name="chk4" id="chk4" class="ads_Checkbox" value="Only Product">Only Product
</td>
</tr>
<tr>
<td colspan="2" class="align-center">
<input type="reset">
<input type="button" id="order" value="Order" onclick="AddData()" />
</td>
</tr>
</table>
</form>
<table cellpadding="4" width="50%" align="center" cellspacing="4" id="mytab" border="1">
<tr>
<th>ShopNmae</th>
<th>Product Name</th>
<th>EmailId</th>
<th>MobileNo</th>
<th>What You Are</th>
<th>Price</th>
<th>Total Product</th>
<th>Total Price</th>
<th>Product With</th>
<th colspan="2">Action</th>
</tr>
<tr id="dummy">
<td colspan="11">No data</td>
</tr>
</table>
I have an html table with one or more row. I have 4 columns in my table in that one is a checkbox. Two buttons are there "AddRowAbove" and "AddRowBelow". When a particular checkbox is checked and click a button a new row should be added based on the button name. My code looks like this not sure how to achieve the result.
function addNewRowAbove() {
alert("actioned !!!");
var rowNumber = document.getElementById("rowIndex").value;
var rowNumberNew = parseInt(rowNumber) - 1;
alert(rowNumber + " - " + rowNumberNew);
var newRow = $('<tr/>').attr('id', 'row' + rowNumberNew);
newRow.html('<td><input type="checkbox" name="radio1" id="radio' + rowNumberNew + '"></input><input type="hidden" id="rowIndex' + rowNumberNew + '" value="' + rowNumberNew + '"/></td><td><input type="text" name="empid" id="empid' + rowNumberNew + '"></input></td><td><input type="text" name="empfname" id="empfname' + rowNumberNew + '"></input></td><td><input type="text" name="emplname" id="emplname' + rowNumberNew + '"></input></td>');
$('#maintable tbody').append(newRow);
}
function addNewRowBelow() {
alert("actioned !!!");
var rowNumber = document.getElementById("rowIndex").value;
var rowNumberNew = parseInt(rowNumber) + 1;
alert(rowNumber + " - " + rowNumberNew);
var newRow = $('<tr/>').attr('id', 'row' + rowNumberNew);
newRow.html('<td><input type="checkbox" name="radio1" id="radio' + rowNumberNew + '"></input><input type="hidden" id="rowIndex' + rowNumberNew + '" value="' + rowNumberNew + '"/></td><td><input type="text" name="empid" id="empid' + rowNumberNew + '"></input></td><td><input type="text" name="empfname" id="empfname' + rowNumberNew + '"></input></td><td><input type="text" name="emplname" id="emplname' + rowNumberNew + '"></input></td>');
$('#maintable tbody').append(newRow);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<table id="maintable" width="50%" cellpadding="0" cellspacing="0" border="#729111 1px solid">
<tr>
<th align="center">Select</th>
<th align="center">Employee ID</th>
<th align="center">First Name</th>
<th align="center">Last Name</th>
</tr>
<tr>
<td><input type="checkbox" name="radio" id="radio"></input><input type="hidden" id="rowIndex" value="1" /></td>
<td><input type="text" name="empid"></input>
</td>
<td><input type="text" name="empfname"></input>
</td>
<td><input type="text" name="emplname"></input>
</td>
</tr>
<tr>
<td><input type="checkbox" name="radio1" id="radio1"></input><input type="hidden" id="rowIndex" value="2" /></td>
<td><input type="text" name="empid1"></input>
</td>
<td><input type="text" name="empfname1"></input>
</td>
<td><input type="text" name="emplname1"></input>
</td>
</tr>
<tr>
<td></td>
<td> <input type="submit" name="AddRowAbove" value="AddRowAbove" onclick="addNewRowAbove()"></td>
<td> <input type="submit" name="AddRowBelow" value="AddRowBelow" onclick="addNewRowBelow()"></td>
<td></td>
</tr>
</table>
</form>
I added var selectedRow = $( "input:checked" ).parent().parent(); to both of your functions to find the parent row of the checked element, and then used either $(newRow).insertBefore(selectedRow); or $(newRow).insertAfter(selectedRow); depending on the button clicked.
Hopefully this helps.
UPDATE:
In response to comments requesting that the id's of the rows are kept in order even after adding rows dynamically, I've added a SortRowIDs() function which is called at the end of both addNewRowAbove() and addNewRowBelow().
This function grabs all of the <input type="checkbox"/> tags in the <table id="maintable"></table> and then iterates through them using jQuery's .each() method. Each checkbox's parent row is then assigned an Id based on its order in the table. I also added a few comments in the code so that it is easier to follow.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
function SortRowIDs() {
// The code below finds all the <tr> elements in the table WITH checkboxes in them.
// This way, we skip the first row containing column headers and the last row containing buttons
// We use the jQuery .each() method to iterate through jQuery-object arrays
$('#maintable').find('tr > td > input[type="checkbox"]').each(function(index) {
// We assign the parent row of the current checkbox to the variable 'currentRow'
let currentRow = $(this).parent().parent();
// Here we give the current row an id based on its position in the table
$(currentRow).attr('id', 'id_' + (index + 1));
// Prints the id's of each row
console.log('Current row\'s id: ' + $(currentRow).attr('id'));
});
// This prints the id attribute of the selected checkbox's parent row, to show that
// the Id's were successfully assigned by the SortRowIDs() function
console.log('');
console.log('Selected row\'s id: ' + $( "input:checked" ).parent().parent().attr('id'));
}
function addNewRowAbove() {
var rowNumber = document.getElementById("rowIndex").value;
var rowNumberNew = parseInt(rowNumber) - 1;
var newRow = $('<tr/>');
newRow.html('<td><input type="checkbox" name="radio1" id="radio' + rowNumberNew + '" /><input type="hidden" id="rowIndex' + rowNumberNew + '" value="' + rowNumberNew + '"/></td><td><input type="text" name="empid" id="empid' + rowNumberNew + '"/></td><td><input type="text" name="empfname" id="empfname' + rowNumberNew + '"></input></td><td><input type="text" name="emplname" id="emplname' + rowNumberNew + '"></input></td>');
var selectedRow = $( "input:checked" ).parent().parent();
$(newRow).insertBefore(selectedRow);
SortRowIDs();
}
function addNewRowBelow() {
var rowNumber = document.getElementById("rowIndex").value;
var rowNumberNew = parseInt(rowNumber) + 1;
var newRow = $('<tr/>');
newRow.html('<td><input type="checkbox" name="radio1" id="radio' + rowNumberNew + '"></input><input type="hidden" id="rowIndex' + rowNumberNew + '" value="' + rowNumberNew + '"/></td><td><input type="text" name="empid" id="empid' + rowNumberNew + '"></input></td><td><input type="text" name="empfname" id="empfname' + rowNumberNew + '"></input></td><td><input type="text" name="emplname" id="emplname' + rowNumberNew + '"></input></td>');
var selectedRow = $( "input:checked" ).parent().parent();
$(newRow).insertAfter(selectedRow);
SortRowIDs();
}
</script>
<form>
<table id="maintable" width="50%" cellpadding="0" cellspacing="0" border="#729111 1px solid">
<tr>
<th align="center">Select</th>
<th align="center">Employee ID</th>
<th align="center">First Name</th>
<th align="center">Last Name</th>
</tr>
<tr>
<td>
<input type="checkbox" name="radio" id="radio"/>
<input type="hidden" id="rowIndex" value="1" />
</td>
<td>
<input type="text" name="empid" />
</td>
<td>
<input type="text" name="empfname" />
</td>
<td>
<input type="text" name="emplname" />
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="radio1" id="radio1" />
<input type="hidden" id="rowIndex" value="2" />
</td>
<td>
<input type="text" name="empid1" />
</td>
<td>
<input type="text" name="empfname1" />
</td>
<td>
<input type="text" name="emplname1" />
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" name="AddRowAbove" value="AddRowAbove" onclick="addNewRowAbove()">
</td>
<td>
<input type="submit" name="AddRowBelow" value="AddRowBelow" onclick="addNewRowBelow()">
</td>
<td></td>
</tr>
</table>
</form>
You can use insertBefore to append new row above buttons (give id="button" to row content buttons). Try with below solution:
function addNewRowAbove(){
alert("actioned !!!");
var rowNumber=document.getElementById("rowIndex").value;
var rowNumberNew = parseInt(rowNumber)- 1 ;
alert(rowNumber+" - "+rowNumberNew);
var newRow = $('<tr/>').attr('id', 'row' + rowNumberNew);
newRow.html('<td><input type="checkbox" name="radio1" id="radio'+rowNumberNew+'"></input><input type="hidden" id="rowIndex'+rowNumberNew+'" value="'+rowNumberNew+'"/></td><td><input type="text" name="empid" id="empid'+rowNumberNew+'"></input></td><td><input type="text" name="empfname" id="empfname'+rowNumberNew+'"></input></td><td><input type="text" name="emplname" id="emplname'+rowNumberNew+'"></input></td>');
newRow.insertBefore('#button');
}
function addNewRowBelow(){
alert("actioned !!!");
var rowNumber=document.getElementById("rowIndex").value;
var rowNumberNew = parseInt(rowNumber) + 1 ;
alert(rowNumber+" - "+rowNumberNew);
var newRow = $('<tr/>').attr('id', 'row' + rowNumberNew);
newRow.html('<td><input type="checkbox" name="radio1" id="radio'+rowNumberNew+'"></input><input type="hidden" id="rowIndex'+rowNumberNew+'" value="'+rowNumberNew+'"/></td><td><input type="text" name="empid" id="empid'+rowNumberNew+'"></input></td><td><input type="text" name="empfname" id="empfname'+rowNumberNew+'"></input></td><td><input type="text" name="emplname" id="emplname'+rowNumberNew+'"></input></td>');
$('#maintable tbody').append(newRow);
}
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<form>
<table id="maintable" width="50%" cellpadding="0" cellspacing="0" border="#729111 1px solid">
<tr>
<th align="center">Select</th>
<th align="center">Employee ID</th>
<th align="center">First Name</th>
<th align="center">Last Name</th>
</tr>
<tr><td><input type="checkbox" name="radio" id="radio"></input><input type="hidden" id="rowIndex" value="1"/></td>
<td><input type="text" name="empid"></input></td>
<td><input type="text" name="empfname"></input></td>
<td><input type="text" name="emplname"></input></td>
</tr>
<tr><td><input type="checkbox" name="radio1" id="radio1"></input><input type="hidden" id="rowIndex" value="2"/></td>
<td><input type="text" name="empid1"></input></td>
<td><input type="text" name="empfname1"></input></td>
<td><input type="text" name="emplname1"></input></td>
</tr>
<tr id="button"><td></td><td> <input type="submit" name="AddRowAbove" value="AddRowAbove" onclick="addNewRowAbove()"></td><td> <input type="submit" name="AddRowBelow" value="AddRowBelow" onclick="addNewRowBelow()"></td><td></td></tr>
</table>
</form>
</body>
</html>