ismaelw
ismaelw

Reputation: 341

jQuery - Calculate sum of input fields including fields added later

I have a form to which you can add more input fields. All have the same class. Whenever an input field is changed I calculate the sum of all those input fields.

It works for all existing fields. As soon as I try it with a newly added field it doesn't work anymore.

I thought that I may have to use the "live" event. But can't figure out how.

This is my code:

$('.price_item').change(function() {
   var ntotal = 0;
   $('.price_item').each(function() {
      ntotal += parseFloat($(this).val());
   });
});

What should I do?

Upvotes: 0

Views: 616

Answers (4)

Rui
Rui

Reputation: 4886

http://api.jquery.com/on/ should work for what you need:

$(document).on('change', '.price_item', handlePriceItemChange);
function handlePriceItemChange(){
  var ntotal = 0;
   $('.price_item').each(function(){
      ntotal += parseFloat($(this).val());
   });
}

Upvotes: 0

Pawel.W
Pawel.W

Reputation: 186

As of jQuery 1.9 you can't use .live(), so you should use .on().

Try something like this:

jQuery(function($){
$(document).on('change', 'input', function(){

    var ntotal = 0;
    $('.price_item').each(function(){
        ntotal += parseFloat($(this).val());
    });

    console.log('sum: ' + ntotal);

    //adds new input for testing
    $(this).after('<input type="text" class="price_item" />');
});               
});

Upvotes: 0

Tricky12
Tricky12

Reputation: 6822

You have to put your event handler on the document since you need this to handle elements that do not exist yet.

$(document).on('change', '.price_item', function() {
    var ntotal = 0;
    $('.price_item').each(function(){
        ntotal += parseFloat($(this).val());
    });
});

Adding a JSFiddle: JSFiddle

Upvotes: 1

Rohan Kumar
Rohan Kumar

Reputation: 40639

Use on() like,

$(document).on('change', '.price_item', function() {
    var ntotal = 0;
    $('.price_item').each(function(){
        ntotal += parseFloat($(this).val());
    });
});

Upvotes: 0

Related Questions