I have a select
element with option
s to choose from. Choosing an option
triggers a callback (in my real project it is a function that creates a new element on the page and loads content into it using an ajax call). I can do it in Firefox either by the select
's change
event handler, or by the option
s' click
event handler (see my code below). This all works perfectly when you do nothing but choose an option and click on it.
The problem starts when you get out of the select
by clicking outside it. For example, if you open the dropdown by a click, but then step through some option
s by using the arrows on the keyboard, then clicking outside the select
produces a select.change
(that's fine) and an option.click
event (that's not so fine, since nobody clicked on an option
). I would still be okay with that (although that gesture means abandoning the element rather than selecting an option), but when you actually click on something that also triggers an event (in real life, for example, creating or destroying elements on the page), it produces a mess.
Speaking of the sample code below, what I want to achieve is that, by one click, either the div
or an option
be click
ed, and never both. (I don't care about the select.change
.)
I have tried both catching and unbinding blur
and focusout
events of the select
, to no avail.
How can I prevent Firefox from triggering an option.click
when the user simply abandons the select
?
Opening the select, moving around with the arrows on the keyboard, then clicking on the div ("click on this div") produces the following output on the JS console:
select was changed
option1 was clicked
div was clicked
I'm using Firefox 50.1. jQuery 1.4.2 is provided by the portal I am to use.
Code:
$('.myDiv')
.click( function (e) {
console.log('div was clicked');
return false;
})
;
$('.mySelect')
.change( function (e) {
console.log('select was changed');
return false;
})
;
$('.mySelect option')
.click( function (e) {
console.log($(this).val() + ' was clicked');
return false;
})
;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<div class='myDiv'>click on this div</div>
<select class='mySelect'>
<option disabled='disabled' selected='selected'>Please select an option</option>
<option>option1</option>
<option>option2</option>
<option>option3</option>
</select>