David
David

Reputation: 10738

jquery through inputs and add them

I had a ton of help from someone to create a jquery code snippet to auto-calculate form inputs based on tax rates. Now i'm trying to figure out how to cycle through each input, add them together and then output them in specific table td's.

I took a crack at adding the sub_total, tax one total, and tax two total and sales tax total but it didn't work. I'd also like for each row's total to the right. I haven't got the slightest idea about how to go about doing that.

heres the jsfiddle that i'm working on. http://jsfiddle.net/SU5jU/20/

perfected --> http://jsfiddle.net/SU5jU/39/

Upvotes: 0

Views: 160

Answers (3)

Marcelo Assis
Marcelo Assis

Reputation: 5194

You're using this to refer to the current input field,inside your each loops, when you should use $(this).

Also, you should parse all input values to float, in your current fiddle you're just joining strings.

http://jsfiddle.net/xvsC7/3/

Upvotes: 3

Samich
Samich

Reputation: 30105

Check this out. I've rewriten your code partially. Maybe it will be useful for you:

Code: http://jsfiddle.net/SU5jU/28/

Main calculation here:

function CalculateData()
{
    var price = parseFloat($(this).val());

    var tax_one_rate = parseFloat($('[name="tax_one_rate"]').val()),
        tax_two_rate = parseFloat($('[name="tax_two_rate"]').val()),
        sales_tax_rate = parseFloat($('[name="sales_tax_rate"]').val());

    var $tr = $(this).parent().parent();
    $tr.find('td input[name="tax_one[]"]').val((tax_one_rate * 0.01 * price).toFixed(2));
    $tr.find('td input[name="tax_two[]"]').val((tax_two_rate * 0.01 * price).toFixed(2));
    $tr.find('td input[name="sales_tax[]"]').val((sales_tax_rate * 0.01 * price).toFixed(2));

    var rowTotal = 0;
    $tr.find('td:gt(1) input').each(function() {
        rowTotal += parseFloat($(this).val());
    });
    $tr.find('#row_total').text((price - rowTotal).toFixed(2));

    CalculateTotal();
}

Upvotes: 0

Rob W
Rob W

Reputation: 349002

You're using the .toFixed method on a String (3x addition of .val()). Convert these strings to a number. Also, you've forgotten to use .val() on your last input element, at var row_total = ..

var row_total = (parseInt($inputs.eq(1).val(), 10)
               + parseInt($inputs.eq(2).val(), 10)
               + parseInt($inputs.eq(3).val(), 10)).toFixed(2);

Finally, replace all occurrences of this.val() by this.value (or $(this).val()).

Fiddle: http://jsfiddle.net/SU5jU/26/

Upvotes: 1

Related Questions