Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery - how to bind a change() function to a dynamically created <select>?

Tags:

jquery

I create elements on the DOM by JS. The question is, how to assign .change() function for each new created element ?

like image 693
Tony Avatar asked Dec 21 '22 21:12

Tony


1 Answers

Even nicer than .live(), from a performance point of view, is .delegate(). This works in the same way as .live(): it uses something called event bubbling, which means that when an event is triggered on a DOM element, that element's parents are all notified of the event. delegate, however, has somewhat nicer syntax and a substantial performance benefit.

$('#parentElement').delegate('select.yourSelectClass', 'change', function() {
    // do your processing here
});

#parentElement can be any selector that matches the common ancestor element of all the select elements that you are going to add. This might be document.body, but there will probably be another element in the DOM tree that you can bind to.

select.yourSelectClass means that the this handler will only be triggered on select elements with the class yourSelectClass. You could change this selector to use any other jQuery selector syntax as you like.

like image 55
lonesomeday Avatar answered May 01 '23 18:05

lonesomeday