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

AndrewC
  • 6,680
  • 13
  • 43
  • 71

3 Answers3

2

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

Andy E
  • 338,112
  • 86
  • 474
  • 445
  • 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? – AndrewC Mar 11 '10 at 14:27
  • @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 Mar 11 '10 at 14:33
  • 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? – AndrewC Mar 11 '10 at 15:10
  • @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 Mar 11 '10 at 15:26
1

Binding click on an option is not possible afaik.

Have a look at 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.

Community
  • 1
  • 1
Fabian
  • 13,603
  • 6
  • 31
  • 53
  • 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? – AndrewC Mar 11 '10 at 14:30
  • 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 Mar 11 '10 at 14:35
0

give each option the same class. e.g <select id='options'><option class='opt' value = '1'>option1/<option class='opt' value = '2'>option2</option></select> now to listen for an event u can just do this: $('.opt').on('click', function(){ alert($('#options').val());});

Emjiz
  • 19
  • 8