views:

282

answers:

2

I have a select with an option it with id 'option1'. option1 is the currently selected option on page load.

In my $(document).ready, I have:

$(document).ready(function()
{
    $("#option1").click(function()
    {
        alert("Testing");
    });
});

However, the alert is never shown and the event never fires! Is it not possible or something to have an event on a select option as opposed to a select itself?

Note:

  1. I don't think I can bind to the select's click() event as I only want the event to fire if the current selected option is clicked on / selected again.
  2. I can't use the select's change() event as I only want it to fire if the currently selected option is clicked on, thus the option won't be changing.

Thanks

+2  A: 

1 is correct, at least in IE (it works in Firefox). onclick will not fire for option elements.

Andy E
Ah.Can you think of any other way I can execute some code, only if the currently selected option (which will always be at index 0) is clicked again?
AndyC
@AndyC: In IE the `onclick` event will fire for the select element when you click on an option. If it's a dropdown select, you could test to see if the mouse coordinates were outside of the select element's boundaries and if the option hasn't changed, do your thing. If it's a multi-select or list, then I'm not really sure.
Andy E
@Andy E for me though it looks like a select element's onclick event fires whenever you click the dropdown, ie BEFORE you click a specific option?
AndyC
@AndyC: That's why I said you need check to see if the mouse is outside the boundaries of the `select` element. If it's within the boundaries, you don't dp anything.
Andy E
A: 

Binding click on an option is not possible afaik.

Have a look at http://stackoverflow.com/questions/1402227/jquery-click-event-on-select-option-element-in-chrome.

Which basically suggest to use the parent select and check if that particular option is selected when fired.

Fabian
The problem is I can't use the select's change() event because I want to execute the code if the option _doesn't_ change (basically they click the currently selected one again.As far as I know, change() will only fire if the user selects an option different to the one already selected?
AndyC
Not the neatest solution, but you could store the current value in a *cough* global *cough* var and compare in in the change event to the new value.
Fabian