Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change my code from a .live() to .on()

I have a live() function in my jquery below:

$("#qandatbl td.weight input").live("change", calculateTotal);

function calculateTotal()
{
   var totalweight = hundred;
   $("#qandatbl td.weight input").each(function (i, elm){
        totalweight = totalweight - parseInt($(elm).val(), 10);
    });

    $("#total-weight").text(totalweight).append('%').css('font-weight', 'bold');
}

Now some people say that the live() function is slowing fading away and that is better to use the on() function. If this is true then how do I change the code above to on() function rather than a live() function? Is it important I don't use live() or does it not really matter that much?

like image 901
BruceyBandit Avatar asked Jan 08 '12 10:01

BruceyBandit


1 Answers

According to the documentation:

Rewriting the .live() method in terms of its successors is straightforward; these are templates for equivalent calls for all three event attachment methods:

$(selector).live(events, data, handler);                // jQuery 1.3+
$(document).delegate(selector, events, data, handler);  // jQuery 1.4.3+
$(document).on(events, selector, data, handler);        // jQuery 1.7+

So in your case, if you're using jQuery 1.7+, it would be:

$(document).on('change', '#qandatbl td.weight input', calculateTotal);
like image 53
Peter-Paul van Gemerden Avatar answered Oct 19 '22 03:10

Peter-Paul van Gemerden