17

The underlying HTML for my drop down has a chance of changing and I was trying to set it up using the .live option rather than the .change option. it does not work for me.

What I currently have is:

$("#ItemsPerPage").change(function(e) { return updatePaging(); });

Unfortuantely, if I update this control via $.ajax it loses the event definition. What I tried, and is not working, is:

$("#ItemsPerPage").live("change", function(e) { return updatePaging(); });

Any thoughts?

3 Answers 3

23

Instead of rebinding the <select> every time, you're better off just swapping its contents (the list of <option> elements) instead.

So use this as you already are:

$("#ItemsPerPage").change(function(e) { return updatePaging(); });

but when you update it, just swap out its contents ( where newSelectElement is the new <select> element):

function updateItemsPerPage( newSelectElement ) {
    $("#ItemsPerPage").empty().append( newSelectElement.childNodes );
}

This way, the binding won't need to be refreshed because the node itself isn't swapped.

Sign up to request clarification or add additional context in comments.

Comments

3

To elaborate on samiz's suggestion, you would need to do something like this:

$(function() {
    bind_items_per_page();
});

function bind_items_per_page() {
    $("#ItemsPerPage").unbind('change').bind('change',function() { 
        updatePaging(); 
    });
}

function updatePaging() {
    $.post('/some/script',{foo:'bar',bar:'foo'},function(data) {
        /* what ever you need to do */
        // And assuming what ever you did above changed your select box...
        bind_items_per_page();
    });
}

Comments

2

The change event is not supported by live(). How about running a function at the end of every AJAX call that reassigns the event definition?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.