I’m building some dynamic select lists with jQuery. When they are changed, I want the event to trigger a function to get a data refresh.
var selector = $('<select id="myid" />');
selector.append($('<option value>Option Placeholder</value>'));
// attach onChange event to select list
selector.bind('change', doUpdate(this));
My problem is that the change event gets fired every time the select list is built. I’m not sure how the trigger is happening– I’d expect it to only trigger the change event when it, well, changes!
When you do this:
what you’re expecting to happen is to bind the event handler to execute the
doUpdatefunction, passingthisas an argument.That isn’t what’s happening. Instead, what it’s doing is calling
doUpdate(this)immediately, and then attempting to set the value returned by that function call as the event handler for thechangeevent.You can simply do:
jQuery will handle the value of
thisfor you (it will be the element triggering the event), so you don’t need to pass it in to the function as an argument.