0

I have a form that should be keeping a running total cost but keyup is not working in the second field. (Note the second field and following fields can be dynamically generated and those do not work either.)

$('.price').keyup(function () {

    var sum = 0;

    $('.price').each(function() {
        sum += Number($(this).val());
    });

    $('#totalPrice1').val(sum);
});

Here's the full JSFiddle: https://jsfiddle.net/statk7y1/

Any help/suggestions would be greatly appreciated. Thx.

stulk
  • 105
  • 2
  • 5
  • 1
    Possible duplicate of [Event binding on dynamically created elements?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – JJJ Sep 16 '16 at 18:30

1 Answers1

0

You need to re-attach the events after you add the new elements. In this way the new added elements will also have the events attached to them: https://jsfiddle.net/tztoc8v0/

var calculateTotal = function() {
    var sum = 0;
    $('.price').each(function() {
        sum += Number($(this).val());
    });
    $('#totalPrice1').val(sum);
}
$(document).ready(function() {
    $('<div/>', {
        'class': 'extraProjecta',
        html: GetHtml()
    }).appendTo('#container');
   $('#addProj').click(function() {
        $('<div/>', {
           'class': 'extraProjecta',
            html: GetHtml()
        }
    ).hide().appendTo('#container').slideDown('slow');

    $('.price').off('keyup').keyup(calculateTotal);

});
$('.price').off('keyup').keyup(calculateTotal);
})

function GetHtml() {

    var len = $('.extraProjecta').length;
    var $html = $('.extraProjectaTemplate').clone();
    $html.find('[name=projCost]')[0].name = "projCost" + len;
    return $html.html();
}

The calculateTotal function is just there so you can save some lines of code and for better maintainable code.

Sergiu
  • 1,186
  • 5
  • 9