jQuery select all inputs with foreach function - javascript

I have 48 inputs, and for each input I need to get its value and add it to the total sum. Currently I am only getting the values of two inputs and adding them but how would it be better to make this a "foreach function"
$(document).ready(function() {
$('.margin .custom-input:nth-child(1)').change(function() {
updateTotal();
});
$('.margin .custom-input:nth-child(2)').change(function() {
updateTotal();
});
var updateTotal = function () {
var input1 = parseInt($('.margin .custom-input:nth-child(1)').val());
var input2 = parseInt($('.margin .custom-input:nth-child(2)').val());
var total = input1 + input2;
$(".marginAttachment").text("Durchschn. Attachmentniveau = " + total + "mm");
};
});
<div class="margin">
<input class="custom-input" type="text" value="0">
</div>

You have to use the jQuery each function. your final code will be like this
$(document).ready(function() {
$('.margin .custom-input').change(function() {
updateTotal();
});
var updateTotal = function () {
var total = 0;
$('.margin .custom-input').each(function() {
total += parseInt($(this).val());
});
$(".marginAttachment").text("Durchschn. Attachmentniveau = " + total + "mm");
};
});
Or, you just directly get the value of active input so that no need to implement for loop. like this
$(document).ready(function() {
var total = 0
$('.margin .custom-input').change(function() {
total += $(this).val()
$(".marginAttachment").text("Durchschn. Attachmentniveau = " + total + "mm");
});
});

jQuery does have foreach support, in form of the .each() function:
var sum = 0;
$('.margin .custom-input').each(function() {
sum += parseInt($(this).val());
});

Related

After click the select option update product price shows wrong in opencart

When I click on selected option product price update shows wrong.
Here is my code
<div class="container">
<div class="row">
<div class="col-md-6">Initial Price: <span id="thisIsOriginal" class="">$45,000.00</span></div>
<div class="col-md-6">Total: <span id="total">$45,000.00</span></div>
</div>
<div class="row">
<select class="optionPrice" name="select-1">
<option value="">Please Select</option>
<option data-price="2,000.00" value="20">+$2,000.00</option>
</select>
</div>
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('.optionPrice').change(function () {
var OriginalPrice = $('#thisIsOriginal').text();
var OriginalCurrency = OriginalPrice.substring(0, 1);
OriginalPrice = OriginalPrice.substring(1);
var total = 0;
$('.optionPrice').each(function () {
if ($(this).find('option:selected').attr('data-price') != 0 && $(this).find('option:selected').attr('data-price') != undefined) {
console.log($('option:selected', this).attr("data-price"));
total += parseFloat($('option:selected', this).attr('data-price'));
}
});
var newTotal = parseFloat(OriginalPrice) + parseFloat(total);
$('#total').text('$' + newTotal.toFixed(2));
});
});
</script>
How to solve this issue.I want after select the price shows 47,000.
The problem with your code is,
Your price contains , inside it. So after parseFloat() the values after the comma is getting truncated. You need to remove the commas before using parseFloat.
Changes need on the following lines,
total += parseFloat($('option:selected', this).attr('data-price').replace(/,/g, ""));
and
var newTotal = parseFloat(OriginalPrice.replace(/,/g, "")) + parseFloat(total);
Updated Fiddle
$('.optionPrice').change(function() {
var OriginalPrice = $('#thisIsOriginal').text();
var OriginalCurrency = OriginalPrice.substring(0, 1);
OriginalPrice = OriginalPrice.substring(1);
var total = 0;
$('.optionPrice').each(function() {
if ($(this).find('option:selected').attr('data-price') != 0 && $(this).find('option:selected').attr('data-price') != undefined) {
console.log($('option:selected', this).attr("data-price"));
total += parseFloat($('option:selected', this).attr('data-price').replace(/,/g, ""));
}
});
var newTotal = parseFloat(OriginalPrice.replace(/,/g, "")) + parseFloat(total);
$('#total').text('$' + newTotal.toFixed(2));
});
Edit for Getting comma separated value,
$('.optionPrice').change(function() {
var OriginalPrice = $('#thisIsOriginal').text();
var OriginalCurrency = OriginalPrice.substring(0, 1);
OriginalPrice = OriginalPrice.substring(1);
var total = 0;
$('.optionPrice').each(function() {
if ($(this).find('option:selected').attr('data-price') != 0 && $(this).find('option:selected').attr('data-price') != undefined) {
console.log($('option:selected', this).attr("data-price"));
total += parseFloat($('option:selected', this).attr('data-price').replace(/,/g, ""));
}
});
var newTotal = parseFloat(OriginalPrice.replace(/,/g, "")) + parseFloat(total);
newTotal = numberWithCommas(newTotal);
$('#total').text('$' + newTotal + ".00");
});
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

Update dynamically generated price of two boxes with select option

I am trying to make this work with the help of jQuery docs but not success so far.
I have two boxes paynow and payfull that has 0 initial value but I am filling these boxes dynamically (jQuery) with product prices.
Now I have to update these values further with select option to discount the price (multiply with data-percent). This is the HTML.
<select class="discount">
<option data-percent="0">Select Discount Coupon</option>
<option data-percent="5">ABCD</option>
<option data-percent="10">EFGH</option>
<option data-percent="15">IJKL</option>
</select>
<span class="price" id="paynow">$0.00</span>
<span class="price" id="payfull">$0.00</span>
EDIT: jQuery code
$(document).ready(function() {
// For Calculator
function Cost_Calculator() {
var Currency = '$';
var messageHTML = 'Please contact us for a price.';
function CostFilter(e) {
return e;
}
//Calculate function
function calculate() {
//Blank!
var CalSaveInfo = [];
$('#cost_calc_custom-data, #cost_calc_breakdown').html('');
//Calculate total
var calCost = 0;
var calculate_class = '.cost_calc_calculate';
$('.cost_calc_active').each(function() {
//Calculation
calCost = calCost + parseFloat($(this).data('value'));
//Add to list
var optionName = $(this).attr('value');
var appendName = '<span class="cost_calc_breakdown_item">' + optionName + '</span>';
var optionCost = $(this).attr('data-value');
var appendCost = '<span class="cost_calc_breakdown_price">' + Currency + optionCost + '</span>';
if (optionCost != "0") {
var appendItem = '<li>' + appendName + appendCost + '</li>';
}
//hidden data
var appendPush = ' d1 ' + optionName + ' d2 d3 ' + optionCost + ' d4 ';
$('#cost_calc_breakdown').append(appendItem);
CalSaveInfo.push(appendPush);
});
//Limit to 2 decimal places
calCost = calCost.toFixed(2);
//Hook on the cost
calCost = CostFilter(calCost);
var CustomData = '#cost_calc_custom-data';
$.each(CalSaveInfo, function(i, v) {
$(CustomData).append(v);
});
//Update price
if (isNaN(calCost)) {
$('#paynow').html(messageHTML);
$('#payfull').html(messageHTML);
$('.addons-box').hide();
} else {
$('#paynow').html(Currency + calCost);
$('#payfull').html(Currency + calCost);
$('.addons-box').show();
}
}
//Calculate on click
$('.cost_calc_calculate').click(function() {
if ($(this).hasClass('single')) {
//Add cost_calc_active class
var row = $(this).data('row');
//Add class to this only
$('.cost_calc_calculate').filter(function() {
return $(this).data('row') == row;
}).removeClass('cost_calc_active');
$(this).addClass('cost_calc_active');
} else {
// Remove class if clicked
if ($(this).hasClass('cost_calc_active')) {
$(this).removeClass('cost_calc_active');
} else {
$(this).addClass('cost_calc_active');
}
}
//Select item
var selectItem = $(this).data('select');
var currentItem = $('.cost_calc_calculate[data-id="' + selectItem + '"]');
var currentRow = currentItem.data('row');
if (selectItem !== undefined) {
if (!$('.cost_calc_calculate[data-row="' + currentRow + '"]').hasClass('cost_calc_active'))
currentItem.addClass('cost_calc_active');
}
//Bring in totals & information
$('#cost_calc_breakdown_container, #cost_calc_clear_calculation').fadeIn();
$('.cost_calc_hide').hide();
$('.cost_calc_calculate').each(function() {
calculate();
});
return true;
});
$('#cost_calc_clear_calculation').click(function() {
$('.cost_calc_active').removeClass('cost_calc_active');
calculate();
$('#cost_calc_breakdown').html('<p id="empty-breakdown">Nothing selected</p>');
return true;
});
}
//Run cost calculator
Cost_Calculator();
});
How about this one:
var totalPayNowPrice=parseFloat($('#paynow').text());
var totalPayFullPrice=parseFloat($('#payfull').text());
$('.discount').on('change',function(){
if(parseInt($('.discount option:selected').attr('data-percent'))){
$('#paynow').text((totalPayNowPrice*parseInt($('.discount option:selected').attr('data-percent')))+'$');
$('#payfull').text((totalPayFullPrice*parseInt($('.discount option:selected').attr('data-percent')))+'$');
}
});
Just put the $ sign in you spans after the numbers, in order to parse function would work.
JSFIDDLE
UPDATE
From another point I think there is a better solution to use prototype and store you current prices in spans inside global variable, then you can use them wherever you want. Here the pseudo prototype for your use, if you`d like just customize it for you using:
function Test(){
this.totalPayNowPrice=1;//the is 1 only for check code working
this.totalPayFullPrice=1;
}
Test.prototype={
init: function(){
var scope=this;
$('.discount').on('change',function(){
if(parseInt($('.discount option:selected').attr('data-percent'))){
$('#paynow').text((scope.totalPayNowPrice*parseInt($('.discount option:selected').attr('data-percent')))+'$');
$('#payfull').text((scope.totalPayFullPrice*parseInt($('.discount option:selected').attr('data-percent')))+'$');
}
},
updatePaynowPrice:function(newPrice){
this.totalPayNowPrice=totalPayNowPrice;
},
updatePayfullPrice:function(newPrice){
this.totalPayFullPrice=totalPayNowPrice;
}
}
you can use
$(document).ready(function(){
// get price from #paynow (just a number)
var getPaynow = $('#paynow').text().match(/\d+/);
// get price from #payfull (just a number)
var getPayfull = $('#payfull').text().match(/\d+/);
$('.discount').on('change', function(){
// get data-percent from selected option
var discount = parseFloat($(this).find('>option:selected').attr('data-percent'));
//alert(discount +'///'+ getPaynow+'///'+ getPayfull);
//update price for #paynow and #payfull
$('#paynow').text('$'+parseFloat(getPaynow - (getPaynow * discount / 100)));
$('#payfull').text('$'+parseFloat(getPayfull - (getPayfull * discount / 100)));
});
});
Working Demo
in your code you can update prices after this part of code
//Update price
if (isNaN(calCost)) {
$('#paynow').html(messageHTML);
$('#payfull').html(messageHTML);
$('.addons-box').hide();
} else {
$('#paynow').html(Currency + calCost);
$('#payfull').html(Currency + calCost);
$('.addons-box').show();
}
//get price from #paynow (just a number)
getPaynow = $('#paynow').text().match(/\d+/);
// get price from #payfull (just a number)
getPayfull = $('#payfull').text().match(/\d+/);

how to get dynamic id of dynamically created textbox in jquery

i want to perform keyup event via textbox id, and all textbox are dynamically created with onclick button event. for this i have to make 20 keyup function. if i use 20 keyup function then my code will become too lengthy and complex. instead of this i want to use a common function for all textbox. can anybody suggest me how to do it..thanks
here is what i am doing to solve it:
<div class="input_fields_wrap">
<button class="add_field_button">Add Booking</button></div>
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
var counter = 2;
$(".add_field_button").click(function() {
if (counter > 10) {
alert("Only 10 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<div id="target"><label>Textbox #' + counter + ' : </label>' +
'<input type="text" name="textbox' + counter +
'" id="firsttextbox' + counter + '" value="" > <input type="text" name="textbox' + counter +
'" id="secondtextbox' + counter + '" value="" > Remove<input type="text" id="box' + counter + '" value="">sum</div>');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
function check(a, b) {
var first = a;
var second = b;
var temp = temp;
var novalue = "";
result = parseInt(first) + parseInt(second);
if (!isNaN(result)) {
return result;
} else {
return novalue;
}
}
$(this).on("keyup", "#firsttextbox2", function(e) {
e.preventDefault();
var a = document.getElementById('firsttextbox2').value;
var b = document.getElementById('secondtextbox2').value;
var number = 2;
result = check(a, b);
document.getElementById('box2').value = result;
});
$(this).on("keyup", "#firsttextbox3", function(e) {
var number = 3;
e.preventDefault();
var a = document.getElementById('firsttextbox3').value;
var b = document.getElementById('secondtextbox3').value;
result = check(a, b);
document.getElementById('box3').value = result;
});
$(this).on("keyup", "#firsttextbox4", function(e) {
var number = 4;
e.preventDefault();
var a = document.getElementById('firsttextbox4').value;
var b = document.getElementById('secondtextbox4').value;
result = check(a, b);
final = document.getElementById('box4').value = result;
});
$(this).on("keyup", "#secondtextbox2", function(e) {
e.preventDefault();
var a = document.getElementById('firsttextbox2').value;
var b = document.getElementById('secondtextbox2').value;
result = check(a, b);
document.getElementById('box2').value = result;
});
$(this).on("keyup", "#secondtextbox3", function(e) {
e.preventDefault();
var a = document.getElementById('firsttextbox3').value;
var b = document.getElementById('secondtextbox3').value;
result = check(a, b);
document.getElementById('box3').value = result;
});
$(this).on("keyup", "#secondtextbox4", function(e) {
e.preventDefault();
var a = document.getElementById('firsttextbox4').value;
var b = document.getElementById('secondtextbox4').value;
result = check(a, b);
document.getElementById('box4').value = result;
});
$(this).on("click", "#remove_field", function(e) { //user click on remove text
e.preventDefault();
$(this).parent('#target').remove();
counter--;
});
});
</script>
See the snippet below to see how you can make this implementation more modular and useable. The trick is to think: what do I want to do? I want to be able to add multiple inputs and add their value, printing the result in another input.
It comes down to using classes - since we are going to use the same kind of thing for every row. Then apply something that works for all classes. No IDs whatsoever! You can even use the name property of the input that contains the value you want to save. Using the [] in that property will even pass you back a nice array when POSTING!
I know this looks like a daunting lot, but remove my comments and the number of lines reduces dramatically and this kind of code is almost infinitely extendable and reusable.
But have a look, this works and its simple and - most of all - it's DRY (don't repeat yourself 0 once you do, re-evaluate as there should be a better way!)!
Update
You could also use a <ol>as a wrapper and then add an <li> to this every time, so you get automatic counting of boxes in the front end without any effort from your end! Actually, thats so nice for this that I have changed my implementation.
var add = $('#add_boxes');
var all = $('#boxes');
var amountOfInputs = 2;
var maximumBoxes = 10;
add.click(function(event){
// create a limit
if($(".box").length >= maximumBoxes){
alert("You cannot have more than 10 boxes!");
return;
}
var listItem = $('<li class="box"></li>');
// we will add 2 boxes here, but we can modify this in the amountOfBoxes value
for(var i = 0; i < amountOfInputs; i++){
listItem.append('<input type="text" class="input" />');
}
listItem.append('<input type="text" class="output" name="value" />');
// Lets add a link to remove this group as well, with a removeGroup class
listItem.append('<input type="button" value="Remove" class="removeGroup" />')
listItem.appendTo(all);
});
// This will tie in ANY input you add to the page. I have added them with the class `input`, but you can use any class you want, as long as you target it correctly.
$(document).on("keyup", "input.input", function(event){
// Get the group
var group = $(this).parent();
// Get the children (all that arent the .output input)
var children = group.children("input:not(.output)");
// Get the input where you want to print the output
var output = group.children(".output");
// Set a value
var value = 0;
// Here we will run through every input and add its value
children.each(function(){
// Add the value of every box. If parseInt fails, add 0.
value += parseInt(this.value) || 0;
});
// Print the output value
output.val(value);
});
// Lets implement your remove field option by removing the groups parent div on click
$(document).on("click", ".removeGroup", function(event){
event.preventDefault();
$(this).parent(".box").remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<ol id="boxes">
</ol>
<input type="button" value="Add a row" id="add_boxes" />
You can target all your textboxes, present or future, whatever their number, with a simple function like this :
$(document).on("keyup", "input[type=text]", function(){
var $textbox = $(this);
console.log($textbox.val());
})
$("button").click(function(){
$("#container").append('<input type="text" /><br>');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<input type="text" /><br>
<input type="text" /><br>
<input type="text" /><br>
</div>
<button>Create one more</button>
You don't need complicated generated IDs, not necessarily a class (except if you have other input[type=text] you don't want to conflict with). And you don't need to duplicate your code and write 20 times the same function. Ever. If you're duplicating code, you're doing wrong.
Add classes "a" and "b" to the textboxes and "box" to the box. Then add data-idx attribute with the index (unused!?). Finally register the event handlers:
$('.a').on('keyup', function(e){
e.preventDefault();
var $this = $(this)
var $p = $this.parent()
var a= this.value;
var b= $p.find('.b').val()
var number =$this.data('idx') //unused!?
var result = check(a,b)
$p.find('.box').val(result)
})
$('.b').on('keyup', function(e){
e.preventDefault();
var $this = $(this)
var $p = $this.parent()
var a= $p.find('.a').val()
var b= this.value
var result = check(a,b)
$p.find('.box').val(result)
})
Or a general one:
$('.a,.b').on('keyup', function(e){
e.preventDefault();
var $p = $(this).parent()
var a= $p.find('.a').val()
var b= $p.find('.b').val()
var result = check(a,b)
$p.find('.box').val(result)
})
You can assign a class to all textboxes on which you want to perform keyup event and than using this class you can attach the event on elements which have that class. Here is an example
var html="";
for (var i = 0; i < 20; i++)
{
html += "<input type='text' id='txt" + i + "' class='someClass' />";
}
$("#testDiv").html(html);
Attach keyup event on elements which have class someClass.
$(".someClass").keyup(function () {
alert($(this).attr("id"));
});
A little helper to combine with your favorite answer:
var uid = function () {
var id = 0;
return function () {
return ++id;
};
}();
Usage:
uid(); // 1
uid(); // 2
uid(); // 3
Providing a code-snippet which may give you some hint:
$(".add_field_button").click(function ()
{
if (counter > 10)
{
alert("Only 10 textboxes allow");
return false;
}
var txtBoxDiv = $("<div id='TextBoxDiv"+counter+"' style='float:left;width:10%; position:relative; margin-left:5px;' align='center'></div>");
//creating the risk weight
var txtBox1 = $('<input />',
{
'id' : 'fst_textbox_' + counter,
'name' : 'textbox'+counter,
'type' : 'text',
'class' : 'input_field',
'onClick' : 'txtBoxFun(this,'+counter+')'
});
var txtBox2 = $('<input />',
{
'id' : 'sec_textbox_' + counter,
'name' : 'textbox'+counter,
'type' : 'text',
'class' : 'input_field',
'onClick' : 'txtBoxFun(this,'+counter+')'
});
var txtBox3 = $('<input />',
{
'id' : 'sum_textbox_' + counter,
'name' : 'textbox'+counter,
'type' : 'text',
'class' : 'input_field',
});
$(txtBoxDiv).append(txtBox1).append(txtBox2);
$(txtBoxDiv).append(txtBox3);
});
function txtBoxFun(obj, count)
{
var idGet = $(obj).attr('id');
var idArr = new Array();
idArr = idGet.split("_");
if(idArr[0] == "fst")
{
var sumTxt = parseInt(parseInt($(obj).val()) + parseInt($("#sec_textbox_"+count).val()));
}
else if(idArr[0] == "sec")
{
var sumTxt = parseInt(parseInt($(obj).val()) + parseInt($("#fst_textbox_"+count).val()));
}
$("#sum_textbox_"+count).val(sumTxt);
}

Javascript data-* attributes calculator

The problem is that a selection of elements sumirovalis each other .. The value of the element specified in the "data-price". My code is not valid and is not handled properly, it is desirable to change the amount at any depression.
Thank you for any assistance conditional
html
<input name="tarifs" id="tarifs2" type="radio" data-price="590" value="Abs">
<input name="tarifs" id="tarifs1" type="radio" data-price="540" value="Abs"><br/>
<input name="tv[]" id="tv3" type="checkbox" data-price="150" value="Abs">
<input name="tv[]" id="tv2" type="checkbox" data-price="100" value="Abs"><br/>
<input name="tv2[]" id="tv4" type="checkbox" data-price="250" value="Abs">
<input name="tv2[]" id="tv5" type="checkbox" data-price="350" value="Abs"><br/>
Sum: <span id="checkout-sum"></span></div>
JS
$("input[name=tarifs]").keyup(function() {
var sum1 = $("input[name=tarifs]").data("price");
var sum2 = $("input[name=tv[]]").data("price");
var sum3 = $("input[name=tv2[]]").data("price");
var total = sum1 + sum2 + sum3;
$("#checkout-sum").val(total);
});
jsfiddle demo
Will use change event and only look for checked inputs. This will work when any of the radios or checkboxes shown changes
$inputs=$('#tarifs1,#tarifs2,#tv2,,#tv3,#tv4,#tv5').change(function(){
var total=0;
$inputs.filter(':checked').each(function(){
total+= $(this).data('price');
});
$("#checkout-sum").text(total);
})
DEMO
Try using this:-
$("input").change(function() {
var sum1 = $("input[name='tarifs']:checked").data("price"),
sum2 = 0,
sum3= 0;
$.each($("input[name='tv[]']:checked"), function(index,item) {
sum2 += $(item).data('price');
});
$.each($("input[name='tv2[]']:checked"), function(index,item) {
sum3 += $(item).data('price');
});
var total = +sum1 + sum2 + sum3;
$("#checkout-sum").html(total);
});
Try this :
Your missing quotes in jQuery selector: $("input[name='tv[]']
$("input[name=tarifs],[name='tv[]'],[name='tv2[]']").change(function() {
var sum1 = $("input[name=tarifs]:checked").data("price");
var sum2 = $("input[name='tv[]']:checked").data("price");
var sum3 = $("input[name='tv2[]']:checked").data("price");
var total = sum1 + sum2 + sum3;
$("#checkout-sum").html(total);
});
Demo
another way:
$input = $("input[name=tarifs],[name='tv[]'],[name='tv2[]']");
$input.change(function() {
var sum = 0;
$input.filter(':checked').each(function(){
sum = sum + $(this).data("price");
});
$("#checkout-sum").html(sum);
});
Demo

Jquery Calculating

I running a similar script to this script from fiddle
http://jsfiddle.net/QmTNZ/2/
I tried to modify it to work with my table.
Here is the link to the table on the product page
http://styleso1.nextmp.net/dev/shop/safari-pu-sleeve-jacket.html
I need it to calculate the Qty ( input box, Column 4) X the unit price ( Column 5 ) and show the sum in column 6
How would i modify the JS to do this?
Here is what i have for the JS
$(function(){
function ca(){
var $overall = 0;
$("tr.sum").each(function() {
var $qnt = $(this).find(".qty");
var $price = $(this).find("td").eq(1);
console.log($qnt + " | " + $price);
var sum = parseFloat($price.text()) * parseFloat($qnt.val());
$(this).find(".a-center1").text(sum);
$overall += sum;
});
$("#total").text($overall);
}
$(function() {
ca();
$('input.qty').bind('change keyup',function(){ca();});
});
Any Help would be very appreciated
Try this
$("tr.sum").each(function() {
var $qnt = $(this).find(".qty");
var $price = $(this).find("td:eq(4)").find('.price');
console.log($qnt + " | " + $price);
var pri = $price.text();
pri = pri.replace('$', '');
var sum = parseFloat(pri) * parseFloat($qnt.val());
$(this).find("td").eq(5).text('$' + sum);
$overall += sum;
});
$("#total").text('$' +$overall);
Check Fiddle
You can save some DOM searching and text parsing by doing some simple things like adding the unit price as a data attribute to the row and retrieving it with jQuery data() method
HTML
<tr class="sum" data-unit_price="10.00">
JS
function ca(){
var $overall = 0;
$("tr.sum").each(function() {
var $row=$(this);
var $qnt = $(this).find(".qty");
var cost = $row.data('unit_price');
var sum = cost * parseFloat($qnt.val());
$(this).find("td").eq(5).text('$' +sum);
$overall += sum;
});
$("#total").text('$' +$overall);
}
$(function() {
ca();
$('input.qty').bind('change keyup', ca);
});
DEMO: http://jsfiddle.net/Jk976/3/

Categories