views:

23

answers:

1

I am trying to bind a simple click event to an the selected option of a pulldown.

$('select#myselect').delegate(':selected', 'click', function()  
{  
    alert('selected');  
});

This code works in Firefox, but not Chrome/Safari. Can I use the .delegate() to bind an option for a pulldown menu like this? If so, how? If not, what is the best alternate solution?

btw, jQuery Click on Event.. gives a potential solution using .change(), but I would like to manage all bindings with .delegate() if possible.

+3  A: 

The click event doesn't fire for <option> elements in these browsers, but whether your options are changing or not, it there's nothing different with:

$('#myselect').change(function() {  
  alert('selected, my new value is: ' + $(this).val());  
});

It comes down to this, there's no need for .delegate() here. .delegate() is used to listen for events that bubble up from descendant elements that may change or are very numerous, when the element itself won't be going anywhere (e.g. replace via AJAX). .live() works in a very similar way, it just listens all the way up on document.

I don't know a better way to explain it other than this: your current usage is not at all what .delegate() is for, it's intended to solve a different problem. You should use .change() here.

Nick Craver
yup right +1 for comprehensive answer :)
Sarfraz
Thanks for the explanation - works great. What feels wrong about the fact that this is the best binding practice is that it is necessary to use multiple jQuery methods to create and manage bindings. This seems to create non-modular code, where bindings are difficult to manage. Maybe there is a plugin that solves this? Maybe a known problem planned for future jQuery versions? Or maybe there is something I'm not understanding about the overall strategy for binding in jQuery.Any thoughts/links would be appreciated.