Question

I have this code...

// Display number of pixels left from nav width
$('.inputs input').live('keyup',function() {
    var nav_width = $('#nav-width').val();
    var sumOfVals = 0;
    $('.inputs input').each(function () {
    sumOfVals = sumOfVals + parseInt($(this).val());
});
sumOfVals = nav_width - sumOfVals;
    $('#px-left em').html(sumOfVals);
});

It needs to be executed on the keyup event of dynamically added input fields but I want to use the 'on' event. Is this possible? I have tried replacing 'live' with 'on' but it didn't work.

Was it helpful?

Solution

You can't just replace live with on. If you read the docs about on you'll see this:

.on( events [, selector] [, data], handler(eventObject) )

So by following that you'd use on like this:

$('.closest-parent').on('keyup', '.inputs input', function () { ... })

.closest-parent is the closest parent element to .inputs. By using the closest parent instead of just document you improve performance.

OTHER TIPS

This should work:

$(document).on('keyup', '.inputs input', function() {
    var nav_width = $('#nav-width').val();
    var sumOfVals = 0;
    $('.inputs input').each(function () {
    sumOfVals = sumOfVals + parseInt($(this).val());
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top