stulk stulk - 2 months ago 16
Javascript Question

jQuery running total function not working on all fields

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.

Answer

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.