Display total sum of values when selecting them - javascript

I have an list with values which is generated by an database query.
I want to see the total sum of values that been selected (by an checkbox) by the user.
Code for checkbox:
<?php
$i = -1;
while ($row = mysql_fetch_array($res))
{
$i++;
?>
echo '<table>
<tr>
<td><input type="checkbox" onclick="bedrag_optellen(this, <?php echo $i ?>);" value= "'.$row['bedrag_incl'].'"></td>
<td>€ '.number_format($row['bedrag_incl'], 2, ',', ' ').'</td>
</tr>
</table>';
}
?>
Code for output field:
<table>
<tr>
<td width="51"><input type="text" id="bedragen_selected" name="bedragen_selected" value="" size="10" style="text-align:right;background-color: #e7e7e9" readonly="readonly" /></td>
</tr>
</table>
JavaScript
<script type="text/javascript"</script>
function bedrag_optellen(checkbox, nr)
{
var i, totaal = 0;
var elems = document.getElementsByName('bedrag_optellen[]');
var l = elems.length;
for(i=0; i<l; i++)
{
if(formElement['bedrag_optellen[]'][i].checked = true)
{
totaal += parseFloat(elems[i].value) || 0;
}
document.getElementById('bedragen_selected').value = totaal.toFixed( 2 );
}
}
</script>
The code is not working, also there is no error given.
Is there anyone to help me out?
https://jsfiddle.net/fawavmbo/

Check out this fiddle.
I have used jQuery for the simplicity it provides.
I made the following changes:
Added a class cost to the checkboxes.
Removed the onClick attribute.
Added jQuery.
For the code to work in you system, add the code below to your <head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Here is the snippet.
HTML
<table>
<tr>
<td><input class='cost' type="checkbox" value= "8"></td>
<td>€ 8</td>
</tr>
<tr>
<td><input class='cost' type="checkbox" value= "3"></td>
<td>€ 3</td>
</tr>
<tr>
<td><input class='cost' type="checkbox" value= "19"></td>
<td>€ 19</td>
</tr>
<tr>
<td><input class='cost' type="checkbox" value= "2"></td>
<td>€ 2</td>
</tr>
<tr>
<td><input class='cost' type="checkbox" value= "15"></td>
<td>€ 15</td>
</tr>
<tr>
<td><input class='cost' type="checkbox" value= "12"></td>
<td>€ 12</td>
</tr>
</table>
<table>
<tr>
<td width="51"><input type="text" id="bedragen_selected" name="bedragen_selected" value="" size="10" style="text-align:right;background-color: #e7e7e9" readonly="readonly" /></td>
</tr>
</table>
JS
var sum = 0;
$('.cost').click(function() {
if($(this).is(':checked')) {
sum = sum + parseInt($(this).val());
} else {
sum = sum - parseInt($(this).val());
}
$('#bedragen_selected').val(sum);
});

Related

how can i get table of values exist in a TD of a table use jquery?

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>

Perform subtraction on table row based on the the input value

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>

Refresh PHP variable after user input

I have a very simple website which helps me to calculate the end of day cash position in my store. Form is here: http://www.073design.nl/kasopmaak/kasopmaak.php#
But now I have to 'click' the "Calculate cash!" button to update the positions.
My questions now; is it possible to add some 'smart' extra code, which updates the totals directly after entering data per line?
Many thanks in advance.
Form uses only this code:
<?php
if(isset($_POST)) {
$total_100 = $_POST['100'] * 100 ;
$total_50 = $_POST['50' ] * 50 ;
$total_20 = $_POST['20' ] * 20 ;
$total_10 = $_POST['10' ] * 10 ;
$total_5 = $_POST['5' ] * 5 ;
$total_2 = $_POST['2' ] * 2 ;
$total_1 = $_POST['1' ] * 1 ;
$total_05 = $_POST['05' ] * 0.5 ;
$total_02 = $_POST['02' ] * 0.2 ;
$total_01 = $_POST['01' ] * 0.1 ;
$total_005 = $_POST['005'] * 0.05 ;
$total = $total_100 + $total_50 + $total_20 + $total_10 + $total_5;
} else {
$total_100 = 0 ;
$total_50 = 0 ;
$total_20 = 0 ;
$total_10 = 0 ;
$total_5 = 0 ;
$total_2 = 0 ;
$total_1 = 0 ;
$total_05 = 0 ;
$total_02 = 0 ;
$total_005 = 0 ;
$total = $total_100 + $total_50 + $total_20 + $total_10 + $total_5 + $total_2 + $total_1 + $total_05 + $total_02 + $total_01 + $total_005 ;
}
?>
<body>
<h1>kas opmaak</h1>
<form action="#" method="POST">
<table>
<tr>
<td><input type="number" name="100" value="<?php echo $_POST['100']; ?>"></td>
<td>X</td>
<td>€ 100</td>
<td> = </td>
<td align="right"><?php echo $total_100;?></td>
</tr>
<tr>
<td><input type="number" name="50" value="<?php echo $_POST['50'];?>"></td>
<td>X</td>
<td>€ 50</td>
<td> = </td>
<td align="right"><?php echo $total_50;?></td>
</tr>
<tr>
<td><input type="number" name="20" value="<?php echo $_POST['20'];?>"></td>
<td>X</td>
<td>€ 20</td>
<td> = </td>
<td align="right"><?php echo $total_20;?></td>
</tr>
<tr>
<td><input type="number" name="10" value="<?php echo $_POST['10'];?>"></td>
<td>X</td>
<td>€ 10</td>
<td> = </td>
<td align="right"><?php echo $total_10;?></td>
</tr>
<tr>
<td><input type="number" name="5" value="<?php echo $_POST['5'];?>"></td>
<td>X</td>
<td>€ 5</td>
<td> = </td>
<td align="right"><?php echo $total_5;?></td>
</tr>
<tr>
<td><input type="number" name="2" value="<?php echo $_POST['2'];?>"></td>
<td>X</td>
<td>€ 2</td>
<td> = </td>
<td align="right"><?php echo $total_2;?></td>
</tr>
<tr>
<td><input type="number" name="1" value="<?php echo $_POST['1'];?>"></td>
<td>X</td>
<td>€ 1</td>
<td> = </td>
<td align="right"><?php echo $total_1;?></td>
</tr>
<tr>
<td><input type="number" name="05" value="<?php echo $_POST['05'];?>"></td>
<td>X</td>
<td>€ 0,50</td>
<td> = </td>
<td align="right"><?php echo $total_05;?></td>
</tr>
<tr>
<td><input type="number" name="02" value="<?php echo $_POST['02'];?>"></td>
<td>X</td>
<td>€ 0,20</td>
<td> = </td>
<td align="right"><?php echo $total_02;?></td>
</tr>
<tr>
<td><input type="number" name="01" value="<?php echo $_POST['01'];?>"></td>
<td>X</td>
<td>€ 0,10</td>
<td> = </td>
<td align="right"><?php echo $total_01;?></td>
</tr>
<tr>
<td><input type="number" name="005" value="<?php echo $_POST['005'];?>"></td>
<td>X</td>
<td>€ 0,05</td>
<td> = </td>
<td align="right"><?php echo $total_005;?></td>
</tr>
<tr>
<td colspan="4"><strong> Totaal contant </strong></td>
<td><?php echo $total;?></td>
</tr>
<tr>
<td colspan="5" align="right"><br/> <input type="submit" value="Calculate cash!"></td>
</tr>
</table>
</form>
It is relatively easy to do this using jquery. I wrote for you a sample code by implement only your first formula [ ] X 100 = [ ]. It can be very easy adapted to cover all your formulas.
When the user enters a number the formula is automatically calculated. It also works with the backspace or delete when the user deletes a number....
Please note that for the case simplicity I avoided to use any error-exception handling code.
It also works without the need of server... ;)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
i = 0;
$(document).ready(function(){
$("#in100").keyup(function(){
$('#out100').get(0).value = $('#in100').get(0).value * 100;
});
});
</script>
</head>
<body>
<input type="text" id="in100" /> X 100 = <input type="text" id="out100" readonly="true" value=""/>
</body>
</html>

Using the same jQuery in multiple operations

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));
});
});

Calculate the sum of products using a td attribute

I have this table :
<table>
<thead>
<tr>
<th>Quantity</th>
<th> </th>
<th>Price</th>
<th>Sum</th>
</tr></thead>
<tbody>
<tr class="sum">
<td><input class="qty" type="text" value="1" /></td>
<td>German format: </td>
<td data_price="1375.5">1.375,50 €</td>
<td></td>
</tr>
<tr class="sum">
<td><input class="qty" type="text" value="1" /></td>
<td>English format:</td>
<td data_price="1375.5">€1,375.50</td>
<td></td>
</tr>
<tr class="sum">
<td><input name="text" type="text" class="qty" value="1" /></td>
<td>French format:</td>
<td data_price="1375.5">1 375,50 €</td>
<td></td>
</tr>
<tr class="sum">
<td><input name="text2" type="text" class="qty" value="1" /></td>
<td>Italian format:</td>
<td data_price="1375.5">€1,375.50</td>
<td></td>
</tr>
<tr class="sum">
<td><input class="qty" type="text" value="1" /></td>
<td>Spanish format:</td>
<td data_price="1375.5">€ 1.375,50</td>
<td></td>
</tr>
<tr>
<td colspan="3">Total</td>
<td id="total"></td>
</tr>
</tbody>
</table>
and I want to use the value of attribute "data_price" to calculate the SUM like in this link :
http://jsfiddle.net/QmTNZ/77/
I want to use only the attribute "data_price" in calculation and not the .
Please help, I'm still beginner in jquery :)
For your price cells, you should use this format:
<td data-price="1375.5">€1,375.50</td>
i.e. with a hyphen, not underscore
You can then use:
$('td').data('price')
to access its value - see http://api.jquery.com/data
e.g.
var sum = 0;
$('.sum').each(function() {
var q = parseFloat($(this).find('.qty').val());
var p = parseFloat($(this).find('td').eq(2).data('price'));
sum += q * p;
});
$('#total').text(sum);
Working demo at http://jsfiddle.net/alnitak/gzYhN/
Try
var sum=0;
$('tbody > tr > td[data_price]').each(
function()
{
sum += parseFloat(this.attr('data_price'));
}
);
Try this: http://jsfiddle.net/ptfKJ/
This example is using your original HTML code.

Categories

Resources