Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery - Adding change event to dropdown

Tags:

jquery

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?

like image 662
Keith Barrows Avatar asked May 07 '09 19:05

Keith Barrows


People also ask

How to trigger a change event in jQuery?

jQuery change() Method The change event occurs when the value of an element has been changed (only works on <input>, <textarea> and <select> elements). The change() method triggers the change event, or attaches a function to run when a change event occurs.

How do you write a single Onchange event for multiple dropdowns?

How to get the values from multiple dropdowns and then trigger a single onchange event. Use a standard jQuery selector. Get all select values. Get the selects with the my-select class.

What event is generated when DropDown values is changed?

ValueChange. ValueChange event triggers when the DropDown List value is changed.


3 Answers

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.

like image 84
Jed Schmidt Avatar answered Oct 29 '22 17:10

Jed Schmidt


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();
    });
}
like image 23
KyleFarris Avatar answered Oct 29 '22 16:10

KyleFarris


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?

like image 39
samiz Avatar answered Oct 29 '22 15:10

samiz