I want to multiply the textbox values and after multiplication sum of all answer values. Example:
SUM (NSP * Current Sales)
This program is working fine but when I change any value it adds the change not replace the values. It should replace the value of array.
And if possible, please minimize the code logic also. Thanks.
$(document).ready(function() {
var val1;
var val2;
var multi;
one();
second();
});
function one() {
$(document).on("change", ".qty1", function() {
var sumqty1 = 0;
sumqty1 += $(this).val();
val1 = sumqty1;
});
}
function second() {
$(document).on("change", ".qty2", function() {
var sumqty1 = 0;
var sumqty2 = 0;
sumqty1 += $(this).closest('tr').find('.qty1').val();
sumqty2 += $(this).val();
val1 = sumqty1;
val2 = sumqty2;
mul(val1, val2);
});
}
var arr = [];
function mul(a, b) {
var hh;
multi = a * b;
arr.push(multi);
var totalsum = 0;
for (var i in arr) {
var value = arr[i];
totalsum = parseInt(totalsum, 10) + parseInt(value, 10);
$("#totalvalue").text(totalsum);
}
console.log(arr);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table style="width: 100%;" width="100%" cellspacing="0">
<thead>
<tr>
<th>Product Name</th>
<th>NSP</th>
<th>Current Sales</th>
<th>Closing Balance</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Product Name</th>
<th>NSP</th>
<th>Current Sales</th>
<th><span id='totalvalue'></span></th>
</tr>
</tfoot>
<tbody>
<tr>
<td>Satou</td>
<td><input type="text" class="qty1" value="1" disabled /></td>
<td><input type="text" class="qty2" value="" /></td>
<td>23</td>
</tr>
<tr>
<td>panadol</td>
<td><input type="text" class="qty1" value="2" disabled /></td>
<td><input type="text" class="qty2" value="" /></td>
<td>131</td>
</tr>
<tr>
<td>disprine</td>
<td><input type="text" class="qty1" value="3" disabled/></td>
<td><input type="text" class="qty2" value="" /></td>
<td>37</td>
</tr>
<tr>
<td>panadol</td>
<td><input type="text" class="qty1" value="4" disabled /></td>
<td><input type="text" class="qty2" value="" /></td>
<td>173</td>
</tr>
</tbody>
</table>
You are continually adding new values into arr and there's a whole lot of shared mutable state going on here.
If there aren't that many rows in the table, you're best off just recalculating the whole total each time a value changes. Less risk of the data stepping on itself that way:
$(document).ready(function() {
$(document).on('change', '.qty1, .qty2', recalculate);
function getTotal() {
return $('#myTable tr')
.toArray()
.map($)
.map(function (row) {
return row.find('.qty1').val() * row.find('.qty2').val();
})
.filter(function (val) { return !Number.isNaN(val); })
.reduce(function (a, b) { return a + b; }, 0);
}
function recalculate() {
$("#totalvalue").text(getTotal());
}
});
<html>
<head>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
</head>
<body>
<table id="myTable" style="width: 100%;" width="100%" cellspacing="0">
<thead>
<tr>
<th>Product Name</th>
<th>NSP</th>
<th>Current Sales</th>
<th>Closing Balance</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Product Name</th>
<th>NSP</th>
<th>Current Sales</th>
<th><span id='totalvalue'></span></th>
</tr>
</tfoot>
<tbody>
<tr>
<td>Satou</td>
<td><input type="text" class="qty1" value="1" disabled /></td>
<td><input type="text" class="qty2" value="" /></td>
<td>23</td>
</tr>
<tr>
<td>panadol</td>
<td><input type="text" class="qty1" value="2" disabled /></td>
<td><input type="text" class="qty2" value="" /></td>
<td>131</td>
</tr>
<tr>
<td>disprine</td>
<td><input type="text" class="qty1" value="3" disabled/></td>
<td><input type="text" class="qty2" value="" /></td>
<td>37</td>
</tr>
<tr>
<td>panadol</td>
<td><input type="text" class="qty1" value="4" disabled /></td>
<td><input type="text" class="qty2" value="" /></td>
<td>173</td>
</tr>
</tbody>
</table>
</body>
</html>
Id say something like:
$(".qty1, .qty2").on("change", function(){
var qty2 = $(".qty2"),
total = 0;
$(".qty1").each(function(ind){
total += $(qty2[ind]).val() * $(this).val();
})
$("#totalvalue").text(total)
})
Added at the end of the document.
Edited a little
The way you have it right now, you're adding new elements to the array in the order they're created, which doesn't allow you to access them later to change them because they could be stored in any order.
The code below saves each value in the array based on the value of val1 so that each element has a designated place in the array. Because of that, you can update any of the values when they are changed, like so:
var arr = [];
function one() {
$(document).on("change", ".qty1", function() {
var sumqty1 = $(this).val();
});
}
function second() {
$(document).on("change", ".qty2", function() {
var val1 = $(this).closest('tr').find('.qty1').val();;
var val2 = $(this).val();
mul(val1, val2);
});
}
function mul(a, b) {
arr[a - 1] = a * b;
var totalsum = 0;
for (var i in arr) {
var value = arr[i];
totalsum = parseInt(totalsum, 10) + parseInt(value, 10);
$("#totalvalue").text(totalsum);
}
console.log(arr);
}
$(document).ready(function() {
one();
second();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table style="width: 100%;" width="100%" cellspacing="0">
<thead>
<tr>
<th>Product Name</th>
<th>NSP</th>
<th>Current Sales</th>
<th>Closing Balance</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Product Name</th>
<th>NSP</th>
<th>Current Sales</th>
<th><span id='totalvalue'></span></th>
</tr>
</tfoot>
<tbody>
<tr>
<td>Satou</td>
<td><input type="text" class="qty1" value="1" disabled /></td>
<td><input type="text" class="qty2" value="" /></td>
<td>23</td>
</tr>
<tr>
<td>panadol</td>
<td><input type="text" class="qty1" value="2" disabled /></td>
<td><input type="text" class="qty2" value="" /></td>
<td>131</td>
</tr>
<tr>
<td>disprine</td>
<td><input type="text" class="qty1" value="3" disabled/></td>
<td><input type="text" class="qty2" value="" /></td>
<td>37</td>
</tr>
<tr>
<td>panadol</td>
<td><input type="text" class="qty1" value="4" disabled /></td>
<td><input type="text" class="qty2" value="" /></td>
<td>173</td>
</tr>
</tbody>
</table>
I also took out some unnecessary code, including:
The hh declaration (since that variable isn't used) in your second() function
a couple of extraneous lines in your one() function
the multi variable
the sumqty1 and sumqty2 variables (you can just use val1 and val2)
Your val1 and val2 variables didn't need to be global, since you are only using them in one function and passing them as parameters to another.
You could also remove the one() function if you want, since those values seem to be static -- but I'm not sure if you allow that value to be changed in your original code.
Related
I am trying to calculate unit total and based on that final total using jQuery, I am able to update unit total every time qty or price is updated, but not able to update final total.
Here is the code:
<table id="tblUpdate" class="dataTable">
<thead>
<tr>
<th>Item</th>
<th>Quantity</th>
<th>Price</th>
<th>Unit Total</th>
</tr>
</thead>
<tbody>
<cfset TotalPrice = 0>
<cfloop query="qItems">
<cfset vLineID = qItems.LineID>
<cfset vUnitTotal = qItems.Quantity * qItems.Price>
<cfset TotalPrice = TotalPrice + vUnitTotal>
<tr data-item-id="#qItems.ItemID#">
<td>#qItems.ItemDescription#</td>
<td><input type="text" name="Quantity_#qItems.LineID#" id="Quantity#vLineID#" class="Quantity" onchange="ChangePrice(#vLineID#,'Quantity');" value="#NumberFormat(qItems.Quantity, '9.99')#" </td>
<td><input type="text" name="Price_#qItems.LineID#" id="UnitPrice#vLineID#" class="Price" onchange="ChangePrice(#vLineID#,'UnitPrice');" value="#NumberFormat(qItems.Price, '9.99')#" </td>
<td id="UnitTotal#vLineID#" class="UnitTotal">#NumberFormat(vUnitTotal,'9.99')#</td>
</tr>
</cfloop>
</tbody>
<tfoot>
<td colspan="4"></td>
<td>Total:</td>
<td id="TotalPrice_Total">#NumberFormat(TotalPrice,'9.99')#</td>
</tfoot>
</table>
And here if the Jquery: The unit total is updating every time when Qty and Price is updated, however, RefreshTotals() function is not updating. Its getting me values but not adding them and calculating final total.
<script>
$(document).ready(function()
{
function ChangePrice(LineID,FieldChanged) {
var Quantity = document.getElementById("Quantity"+LineID);
var UnitPrice = document.getElementById("UnitPrice"+LineID);
var TotalPrice = 0;
var vQuantity = Quantity.value;
var vUnitPrice = UnitPrice.value;
if (FieldChanged == "Quantity" || FieldChanged == "UnitPrice") {
vCustomTotal = vQuantity * vUnitPrice;
$('#UnitTotal' + LineID).text(vCustomTotal.toFixed(2));
}
refreshTotals();
}
function refreshTotals() {
var vTotalPrice = 0;
$('.UnitTotal').each(function(index) {
var r = $("#tblUpdate.UnitTotal").text();
vTotalPrice = vTotalPrice + r;
});
$('#TotalPrice_Total').text(vTotalPrice.toFixed(2));
}
}
</script>
Consider the following example.
$(function() {
function formatCurrency(f) {
return "$" + parseFloat(f).toFixed(2);
}
function refreshTotals() {
var vTotalPrice = 0;
var r;
$(".UnitTotal").each(function(index, element) {
r = parseFloat($(element).text().trim().substring(1));
vTotalPrice += r;
});
$('#TotalPrice_Total').text(formatCurrency(vTotalPrice));
}
function changePrice(Row) {
var Quantity = parseInt($(".Quantity", Row).val());
var UnitPrice = parseFloat($(".Price", Row).val().substring(1));
var TotalPrice = Quantity * UnitPrice;
$(".UnitTotal", Row).html(formatCurrency(TotalPrice));
refreshTotals();
}
$(".Quantity, .Price").change(function() {
changePrice($(this).closest("tr"));
});
refreshTotals();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tblUpdate" class="dataTable">
<thead>
<tr>
<th>Item</th>
<th>Quantity</th>
<th>Price</th>
<th>Unit Total</th>
</tr>
</thead>
<tbody>
<tr data-item-id="01">
<td>Item 01</td>
<td><input type="number" min="0" max="999" name="Quantity_01" id="Quantity01" class="Quantity" value="9" /></td>
<td><input type="text" name="Price_01" id="UnitPrice01" class="Price" value="$9.99" /> </td>
<td id="UnitTotal01" class="UnitTotal">$89.91</td>
</tr>
<tr data-item-id="02">
<td>Item 02</td>
<td><input type="number" min="0" max="999" name="Quantity_02" id="Quantity02" class="Quantity" value="6" /></td>
<td><input type="text" name="Price_02" id="UnitPrice02" class="Price" value="$8.88" /> </td>
<td id="UnitTotal01" class="UnitTotal">$53.28</td>
</tr>
<tr data-item-id="03">
<td>Item 03</td>
<td><input type="number" min="0" max="999" name="Quantity_03" id="Quantity03" class="Quantity" value="3" /></td>
<td><input type="text" name="Price_03" id="UnitPrice03" class="Price" value="$7.77" /> </td>
<td id="UnitTotal03" class="UnitTotal">$23.31</td>
</tr>
</tbody>
<tfoot>
<td colspan="2"></td>
<td>Total:</td>
<td id="TotalPrice_Total">$0.00</td>
</tfoot>
</table>
When there are changes to Quantity or Price, the total Unit Price is updated along with the Total. We can pass in the Row and then collect all the details needed from that Row. The value of an input is String so it is best to cast it into the proper Integer or Float as needed. This will ensure that Math operations are correct.
i want when i check checkbox in table get array values check (NAME, FIRST NAME, SALAIRENET) in example below it gives me just SALAIRENET and give NaN a name for the line check, please help me.
he is my table
<table class="table table-bordered" id="mytable">
<tr>
<th>Archive</th>
<th><input type="checkbox" id="check_all"></th>
<th>S.No.</th>
<th>matricule</th>
<th>nom & prenom</th>
<th>salaire net</th>
<th>nbre de jour </th>
<th>prime</th>
</tr>
#if($salaries->count())
#foreach($salaries as $key => $salarie)
<tr id="tr_{{$salarie->id}}">
<td>archive</td>
<td><input type="checkbox" class="checkbox" data-id="{{$salarie->id}}"></td>
<td>{{ ++$key }}</td>
<td>{{ $salarie->matricule }}</td>
<td class="name">{{ $salarie->nom }} {{ $salarie->prenom }}</td>
<td class="salaireValue">{{ $salarie->salairenet }}</td>
<td><input type="text" name="nbreJ" class="form-control" value="{{$data['nbr']}}"></td>
<td><input type="text" name="prime" class="form-control" value="0"></td>
</tr>
#endforeach
#endif
</table>
he is my code jquery:
<script type="text/javascript">
$(document).ready(function () {
$('#check_all').on('click', function(e) {
if($(this).is(':checked',true))
{
$(".checkbox").prop('checked', true);
} else {
$(".checkbox").prop('checked',false);
}
});
$('.checkbox').on('click',function(){
if($('.checkbox:checked').length == $('.checkbox').length){
$('#check_all').prop('checked',true);
}else{
$('#check_all').prop('checked',false);
}
});
//get value
$('.table').on('click', function() {
var allChecked = $('.checkbox:checked');
for (var i = 0; i < allChecked.length; i++) {
var currentHtml = $(allChecked[i]).parent().siblings('.salaireValue')[0];
var currentHtml1 = $(allChecked[i]).parent().siblings('.name')[0];
var result = parseInt($(currentHtml)[0].innerText);
var result1 = parseInt($(currentHtml1)[0].innerText);
console.log(result);
console.log(result1);
}
});
});
</script>
It might be helpful to create functions to break up the work. Also you can use parseInt() but it must receive a String that represents an Integer, so "1000" versus "One Thousand".
Consider the following:
$(function() {
function checkToggleAll(c, v) {
$(".checkbox", c).each(function(i, el) {
$(el).prop("checked", v);
});
}
function checkAll(c) {
if ($(".checkbox:checked", c).length == $(".checkbox", c).length) {
$("#check_all").prop("checked", true);
} else {
$("#check_all").prop("checked", false);
}
}
function gatherData(c) {
var rows = {}
$(".checkbox:checked", c).each(function(i, el) {
var row = $(el).parent().parent();
rows[row.attr("id")] = {
Name: $(".first-name", row).text().trim(),
SurName: $(".sur-name", row).text().trim(),
SalaireValue: parseInt($(".salaireValue", row).text().trim())
};
});
return rows;
}
$("#check_all").change(function() {
checkToggleAll($("tbody"), $(this).prop("checked"));
console.log(gatherData($(".table tbody")));
});
$("tbody .checkbox").on("change", function() {
checkAll($(".table tbody"));
console.log(gatherData($(".table tbody")));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-bordered" id="mytable">
<thead>
<tr>
<th>Archive</th>
<th><input type="checkbox" id="check_all"></th>
<th>S.No.</th>
<th>matricule</th>
<th>nom & prenom</th>
<th>salaire net</th>
<th>nbre de jour </th>
<th>prime</th>
</tr>
</thead>
<tbody>
<tr id="tr_1">
<td>archive</td>
<td><input type="checkbox" class="checkbox" data-id="1"></td>
<td>1</td>
<td>1001</td>
<td class="name">Simpson, Homer</td>
<td class="salaireValue">60000</td>
<td><input type="text" name="nbreJ" class="form-control" value="40"></td>
<td><input type="text" name="prime" class="form-control" value="0"></td>
</tr>
<tr id="tr_2">
<td>archive</td>
<td><input type="checkbox" class="checkbox" data-id="2"></td>
<td>2</td>
<td>1002</td>
<td class="name">Leonard, Lenny</td>
<td class="salaireValue">40000</td>
<td><input type="text" name="nbreJ" class="form-control" value="40"></td>
<td><input type="text" name="prime" class="form-control" value="0"></td>
</tr>
<tr id="tr_3">
<td>archive</td>
<td><input type="checkbox" class="checkbox" data-id="3"></td>
<td>3</td>
<td>1002</td>
<td class="name">Carlson, Carl</td>
<td class="salaireValue">55000</td>
<td><input type="text" name="nbreJ" class="form-control" value="40"></td>
<td><input type="text" name="prime" class="form-control" value="0"></td>
</tr>
</tbody>
</table>
I assume that the table content might get updated dynamically, so I am using .on() just in case. You can use .change() if needed.
Hope that helps.
A few changes in your for loop will make it:
for (var i = 0; i < allChecked.length; i++) {
var $tr = $(allChecked[i]).closest("tr");
var item = {
Name: $tr.find(".first-name").text(),
SurName: $tr.find(".sur-name").text(),
SalaireValue: $tr.find(".salaireValue").text()
};
console.log(item);
}
I've also separated the names into two spans in order to make it easy to select them.
$('#check_all').on('click', function(e) {
if($(this).is(':checked',true))
{
$(".checkbox").prop('checked', true);
} else {
$(".checkbox").prop('checked',false);
}
});
$('.checkbox').on('click',function(){
if($('.checkbox:checked').length == $('.checkbox').length){
$('#check_all').prop('checked',true);
}else{
$('#check_all').prop('checked',false);
}
});
//get value
$('.table').on('click', function() {
var allChecked = $('.checkbox:checked');
for (var i = 0; i < allChecked.length; i++) {
var $tr = $(allChecked[i]).closest("tr");
var item = {
Name: $tr.find(".first-name").text(),
SurName: $tr.find(".sur-name").text(),
SalaireValue: $tr.find(".salaireValue").text()
};
console.log(item);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-bordered" id="mytable">
<tr>
<th>Archive</th>
<th><input type="checkbox" id="check_all"></th>
<th>S.No.</th>
<th>matricule</th>
<th>nom & prenom</th>
<th>salaire net</th>
<th>nbre de jour </th>
<th>prime</th>
</tr>
<tr id="tr_1">
<td>archive</td>
<td><input type="checkbox" class="checkbox" data-id="1"></td>
<td>1</td>
<td>1</td>
<td class="name"><span class='first-name'>Name</span> <span class='sur-name'>Surname</span></td>
<td class="salaireValue">123</td>
<td><input type="text" name="nbreJ" class="form-control" value="1"></td>
<td><input type="text" name="prime" class="form-control" value="0"></td>
</tr>
<tr id="tr_2">
<td>archive</td>
<td><input type="checkbox" class="checkbox" data-id="2"></td>
<td>2</td>
<td>2</td>
<td class="name"><span class='first-name'>Name</span> <span class='sur-name'>Surname</span></td>
<td class="salaireValue">456</td>
<td><input type="text" name="nbreJ" class="form-control" value="1"></td>
<td><input type="text" name="prime" class="form-control" value="0"></td>
</tr>
</table>
I was wondering If the payment status is Y, can the price be subtracted accordingly. The amount yet to be paid will show the subtraction result
For example, in this case, since both 50 and 10 is paid,
the amount yet to be paid will be the "total (ie 70) minus (50+10)" = 10
Many thanks.
$(document).ready(function(){
$("#myTable").on('input', '.txtCal', function () {
calculate();
});
function calculate() {
var calculated_total_sum = 0;
$("#myTable .txtCal").each(function () {
var get_textbox_value = $(this).val();
if ($.isNumeric(get_textbox_value)) {
calculated_total_sum += parseFloat(get_textbox_value);
}
});
$("#total_sum_value").html(calculated_total_sum);
}
calculate();
});
<html>
<head><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body>
<table id="myTable">
<tr> <th width="100">Name </th>
<th>Price</th><th>Payment status</th>
</tr>
<tr>
<td><span>A</span></td>
<td><input type="text" class='txtCal' value="50" /></td>
<td><input type="text" class='status' value="Y" /></td>
</tr>
<tr>
<td><span>B :</span></td>
<td><input type="text" class='txtCal' value="10" /></td>
<td><input type="text" class='status' value="Y" /></td>
</tr>
<tr>
<td><span>C:</span></td>
<td><input type="text" class='txtCal' value="10" /></td>
<td><input type="text" class='status' value="N" /></td>
</tr>
<tr>
<td><span><b>TOTAL :</b></span></td>
<td><b><span id="total_sum_value"></span></b></td>
</tr>
<tr>
<td><span><b>Yet to be paid</b></span></td>
<td><b><span id="arrears"></span></b></td>
</tr>
</table>
Yes, you can check the payment status column for N and sum those values. Like this:
$(document).ready(function() {
$("#myTable").on('input', '.txtCal, .status', function() {
calculate();
});
function calculate() {
var calculated_total_sum = 0;
var to_be_paid = 0;
$("#myTable tr").each(function() {
var get_textbox_value = $('.txtCal', this).val();
var get_payment_status = $('.status', this).val();
if (get_textbox_value && get_payment_status) {
if ($.isNumeric(get_textbox_value)) {
calculated_total_sum += parseFloat(get_textbox_value);
}
if (get_payment_status === 'N') {
to_be_paid += parseFloat(get_textbox_value);
}
}
});
$("#total_sum_value").html(calculated_total_sum);
$("#arrears").html(to_be_paid);
}
calculate();
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body>
<table id="myTable">
<tr>
<th width="100">Name </th>
<th>Price</th>
<th>Payment status</th>
</tr>
<tr>
<td><span>A</span></td>
<td><input type="text" class='txtCal' value="50" /></td>
<td><input type="text" class='status' value="Y" /></td>
</tr>
<tr>
<td><span>B :</span></td>
<td><input type="text" class='txtCal' value="10" /></td>
<td><input type="text" class='status' value="Y" /></td>
</tr>
<tr>
<td><span>C:</span></td>
<td><input type="text" class='txtCal' value="10" /></td>
<td><input type="text" class='status' value="N" /></td>
</tr>
<tr>
<td><span><b>TOTAL :</b></span></td>
<td><b><span id="total_sum_value"></span></b></td>
</tr>
<tr>
<td><span><b>Yet to be paid</b></span></td>
<td><b><span id="arrears"></span></b></td>
</tr>
</table>
Another solution would be, getting the parent for every iteration, it might a little less performance friendly but here you go:
$(document).ready(function(){
$("#myTable").on('input', '.txtCal', function () {
calculate();
});
function calculate() {
var calculated_total_sum = 0;
var yet_to_be_paid = 0;
$("#myTable .txtCal").each(function () {
var get_textbox_value = $(this).val();
if ($.isNumeric(get_textbox_value)) {
calculated_total_sum += parseFloat(get_textbox_value);
}
if($(this).parent().parent().find(".status").first().val() == "Y") {
yet_to_be_paid += parseFloat($(this).val());
}
});
$("#total_sum_value").html(calculated_total_sum);
$("#arrears").html(calculated_total_sum - yet_to_be_paid);
}
calculate();
});
<html>
<head><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body>
<table id="myTable">
<tr> <th width="100">Name </th>
<th>Price</th><th>Payment status</th>
</tr>
<tr>
<td><span>A</span></td>
<td><input type="text" class='txtCal' value="50" /></td>
<td><input type="text" class='status' value="Y" /></td>
</tr>
<tr>
<td><span>B :</span></td>
<td><input type="text" class='txtCal' value="10" /></td>
<td><input type="text" class='status' value="Y" /></td>
</tr>
<tr>
<td><span>C:</span></td>
<td><input type="text" class='txtCal' value="10" /></td>
<td><input type="text" class='status' value="N" /></td>
</tr>
<tr>
<td><span><b>TOTAL :</b></span></td>
<td><b><span id="total_sum_value"></span></b></td>
</tr>
<tr>
<td><span><b>Yet to be paid</b></span></td>
<td><b><span id="arrears"></span></b></td>
</tr>
</table>
I'm trying to clone the last row of my table and append it to the table, with blank values, when you press tab on the last name input field. so I wrote the code below. it works great until you get to the second line, it doesn't seem to clone and append the row if it's a clone. is there a way around this / What am I doing wrong?
$(document).ready(function() {
var $last_name = $('.last_name');
var $blank_row = $('tr:last');
var $time_table = $('#time_table');
$last_name.keydown(function(e) {
if (e.which === 9) {
$blank_row.clone().find('input').val('').end().appendTo($time_table);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="time_table">
<tr>
<th>Last Name</th>
<th>First Name</th>
<th>Rate</th>
<th class="time">ST</th>
<th class="time">TH</th>
<th class="time">DT</th>
<th class="time">EX-ST</th>
<th class="time">EX-TH</th>
<th class="time">EX-DT</th>
</tr>
<tr class="blank_row">
<td><input type="text" name="last_name" class="last_name"></td>
<td><input type="text" name="first_name"></td>
<td><input type="text" name="rate"></td>
<td><input type="number" name="st" class="time_input"></td>
<td><input type="number" name="th" class="time_input"></td>
<td><input type="number" name="dt" class="time_input"></td>
<td><input type="number" name="ex_st" class="time_input"></td>
<td><input type="number" name="ex_th" class="time_input"></td>
<td><input type="number" name="ex_dt" class="time_input"></td>
</tr>
</table>
Because .last_name is added dynamically — variable $last_name stores a reference to the first empty row.
https://api.jquery.com/on/
$(document).ready(function() {
var $time_table = $('#time_table');
$time_table.on('keydown', '.last_name', function(e) {
if (e.which === 9) {
$('tr:last').clone().find('input').val('').end().appendTo($time_table);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="time_table">
<tr>
<th>Last Name</th>
<th>First Name</th>
<th>Rate</th>
<th class="time">ST</th>
<th class="time">TH</th>
<th class="time">DT</th>
<th class="time">EX-ST</th>
<th class="time">EX-TH</th>
<th class="time">EX-DT</th>
</tr>
<tr class="blank_row">
<td><input type="text" name="last_name" class="last_name"></td>
<td><input type="text" name="first_name"></td>
<td><input type="text" name="rate"></td>
<td><input type="number" name="st" class="time_input"></td>
<td><input type="number" name="th" class="time_input"></td>
<td><input type="number" name="dt" class="time_input"></td>
<td><input type="number" name="ex_st" class="time_input"></td>
<td><input type="number" name="ex_th" class="time_input"></td>
<td><input type="number" name="ex_dt" class="time_input"></td>
</tr>
</table>
Try this:
The keydown() binding you're using is called a "direct" binding which will only attach the handler to elements that already exist. It won't get bound to elements created dynamically. To do that, need to create a "delegated" binding by using on().
$(document).ready(function () {
var $last_name = 'input.last_name';
var $blank_row = $('tr:last');
var $time_table = $('#time_table');
$("#time_table").on("keydown", $last_name, function (e) {
if (e.which === 9) {
$blank_row.clone().find('input').val('').end().appendTo($time_table);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="time_table">
<tr>
<th>Last Name</th>
<th>First Name</th>
<th>Rate</th>
<th class="time">ST</th>
<th class="time">TH</th>
<th class="time">DT</th>
<th class="time">EX-ST</th>
<th class="time">EX-TH</th>
<th class="time">EX-DT</th>
</tr>
<tr class="blank_row">
<td><input type="text" name="last_name" class="last_name"></td>
<td><input type="text" name="first_name"></td>
<td><input type="text" name="rate"></td>
<td><input type="number" name="st" class="time_input"></td>
<td><input type="number" name="th" class="time_input"></td>
<td><input type="number" name="dt" class="time_input"></td>
<td><input type="number" name="ex_st" class="time_input"></td>
<td><input type="number" name="ex_th" class="time_input"></td>
<td><input type="number" name="ex_dt" class="time_input"></td>
</tr>
</table>
I have a small question and I hope someone can help me with it :D
I’m trying to create a product table, in which a user just add the quantity of a product and the jquery makes the multiplication to its value and gives the result
I already made this, and it works well:
<script>
$(document).ready(function(){
$('#quantity_1').keyup(function(){
var price_1 = $("#price_1").val();
var quantity_1 = $("#quantity_1").val();
quantity_1 = quantity_1.replace(/[^0-9]+/g, '');
$("#quantity_1").val(quantity_1);
var total_1 = price_1 * quantity_1;
$( "#total_1" ).val( total_1.toFixed(2) );
});
});
</script>
<table border="1" cellpadding="5px" cellspacing="0" >
<tr>
<td>Product</td>
<td>Price</td>
<td>Quantity</td>
<td>Total</td>
</tr>
<tr>
<td>Product Name</td>
<td><input type="hidden" name="product[1][price]" id="price_1" value="10.00" />10.00</td>
<td><input type="text" name="product[1][quantity]" id="quantity_1" /></td>
<td><input type="text" name="product[1][total]" id="total_1" value="0" /></td>
</tr>
</table>
Working demo here:
http://jsfiddle.net/EnterateNorte/9kswL0gf/
But I would like to be able to add more than one line, like so:
<table border="1" cellpadding="5px" cellspacing="0" >
<tr>
<td>Product</td>
<td>Price</td>
<td>Quantity</td>
<td>Total</td>
</tr>
<tr>
<td>Name 1</td>
<td><input type="hidden" name="product[1][price]" id="price_1" value="10.00" />10.00</td>
<td><input type="text" name="product[1][quantity]" id="quantity_1" /></td>
<td><input type="text" name="product[1][total]" id="total_1" value="0" /></td>
</tr>
<tr>
<td>Name 5</td>
<td><input type="hidden" name="product[5][price]" id="price_5" value="10.00" />23.00</td>
<td><input type="text" name="product[5][quantity]" id="quantity_5" /></td>
<td><input type="text" name="product[5][total]" id="total_5" value="0" /></td>
</tr>
<tr>
<td>Name 3</td>
<td><input type="hidden" name="product[3][price]" id="price_3" value="130.00" />10.00</td>
<td><input type="text" name="product[3][quantity]" id="quantity_3" /></td>
<td><input type="text" name="product[3][total]" id="total_3" value="0" /></td>
</tr>
<tr>
<td>Name 4</td>
<td><input type="hidden" name="product[4][price]" id="price_4" value="12.00" />10.00</td>
<td><input type="text" name="product[4][quantity]" id="quantity_4" /></td>
<td><input type="text" name="product[4][total]" id="total_4" value="0" /></td>
</tr>
</table>
And if it isn’t to much trouble, I would be awesome if it would SUM all the totals and show a gran total at the end of the table :)
Use:
$(document).ready(function(){
$('[name*=quantity]').keyup(function(){
var price = $(this).parent().prev().find('input').val();
var quantity = $(this).val();
var total = price * quantity;
$(this).parent().next().find('input').val( total.toFixed(2) );
});});
Working Demo
Update: For showing Grand Total
var sum = 0;
//iterate through each textboxes and add the values
$('[name*=total]').each(function() {
//add only if the value is number
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseInt(this.value);
}
});
Working Demo
What you can do is to find the elements using their relative position instead of hard coded ids
$(document).ready(function () {
$('input[id^="quantity_"]').keyup(function () {
var $tr = $(this).closest('tr');
var price = $tr.find('input[id^="price_"]').val();
var quantity = this.value;
var total = (price * quantity) || 0;
$tr.find('input[id^="total_"]').val(total.toFixed(2));
});
});
Demo: Fiddle
I've updated your code in Fiddle. You need to change in your markup a bit.
<tr>
<td>Product Name</td>
<td><input type="hidden" class="price" ... />10</td>
<td><input type="text" class="quantity" ... /></td>
<td><input type="text" class="total" ... /></td>
</tr>
$(document).ready(function(){
$('.quantity').keyup(function(){
var parent = $(this).closest("tr");
var price = $(".price", parent).val();
var quantity = $(".quantity", parent).val();
var total = price * quantity;
$(".total", parent).val(total.toFixed(2));
});
});
I would recommend you to use common class
HTML:
<tr>
<td>Name 5</td>
<td>
<input type="hidden" class="price" value="10.00" />10.00</td>
<td>
<input type="text" class="quantity" />
</td>
<td>
<input type="text" class="total" value="0" />
</td>
</tr>
<tr>
<td>Name 3</td>
<td>
<input type="hidden" class="price" value="130.00" />130.00</td>
<td>
<input type="text" class="quantity" />
</td>
<td>
<input type="text" class="total" value="0" />
</td>
</tr>
Script:
$('.quantity').keyup(function () {
var tr = $(this).closest('tr');
var price = tr.find('.price').val();
var quantity = $(this).val();
var total = price * quantity;
tr.find('.total').val(total.toFixed(2));
});
DEMO
Modify your table:
<table border="1" cellpadding="5px" cellspacing="0" id='table' >
<!-- your rows with inputs -->
<tr>
<td>
<input id='totalSum' value='0' type='text' />
</td>
</tr>
</table>
Make all your 'total' inputs readonly by adding 'readonly' attribute.
js code:
$(document).ready(function(){
$('[name*=quantity]').keyup(function(){
var total = 0;
$('#table tr').each(function(i,item){
var price = parseFloat($(item).find('[name*=price]').val().replace(',','.'));
var quantity = parseInt($(item).find('[name*=quantity]').val());
if(!isNaN(price) && !isNan(quantity)){
total += price*quantity;
}
});
$("#totalSum").val(total.toFixed(2));
});
});