Search code examples
jquerylive

jQuery live() not working.. probably doing it wrong?


I have a paged list of items, each with a checkbox associated with it.

If I click a checkbox, I write that checkbox's id to a cookie. When the page reloads, i want to re-check all the previously selected checkboxes.

This works fine with the following code:

$('.fund-compare-check-box').each(function () {
    var cookie = getCookie("fund_basket").split("|");

    // re-check all check boxes
});

The problem I have with this, is when I load the next page of results. The code above only runs when the DOM is ready.

I thought I could fix this by using .live() instead of .each(), as follows:

$('.fund-compare-check-box').live('each', function () {
    var cookie = getCookie("fund_basket").split("|");

    // re-check all check boxes
});

but when I use this, nothing happens at all. Am I doing this wrong? Any pointers would be much appreciated!


Solution

  • live is for binding event handlers to elements that may or may not currently exist. The first argument is the event type. Your code binds a function to the each event on elements that match your selector. Obviously, the each event does not exist.

    You probably want your code to be executed after every AJAX query (I'm presuming your elements are being added through AJAX). If this is the case, you may like to use ajaxComplete:

    $(document).ajaxComplete(function() {
        $('.fund-compare-check-box').each(function () {
            var cookie = getCookie("fund_basket").split("|");
    
            // re-check all check boxes
        });
    });
    

    If your content is added in a different way, you'll have to figure out some way to call that function each time the content is added.