I'm triying to open an select after a button click, But it doesnt work. If I insert and alert() after the trigger the it opens...
(Using chosen v1.0 with jquery)
example:
<select id="select">
<option value="1">a</option>
<option value="2">b</option>
<option value="3">c</option>
</select>
<br>
<button onclick="$('#select').trigger('chosen:open'); ">Press this button to open (doesnt work) </button>
<button onclick="$('#select').trigger('chosen:open'); alert('ups!');">Press this button to open (work???)</button>
<script>
$(document).ready(function() {
$('#select').chosen();
});
</script>
example in: http://jsfiddle.net/EArg6/28/
Neither button works for me in your Fiddle (in Safari).
What browser/version are you using?
I tested it with:
The first button dont work
The second button open the option list (only to close when the I close the "alert" box).
When you click the button, Chosen is receiving the chosen:open
event. However, the event continues to bubble up the DOM and Chosen is immediately detecting a click on an element that is not the active Chosen ... so it closes it. Make sense?
If you are working with inline JS, the easiest solution is to use setTimeout
to break out of the current event stack:
onClick="setTimeout(function(){ $('#select').trigger('chosen:open'); }, 0)"
You almost certainly shouldn't be using inline JS, though. You can still use setTimeout
if you want, but just stopping the event bubbling should be good enough.
$('button').on("click", function(evt){
evt.stopPropagation();
$('#select').trigger('chosen:open');
});
I've updated your fiddle with this working code: http://jsfiddle.net/EArg6/33/
thanks @pfiller
Thanks @pfiller, that solution and explanation saved me a lot of heartburn!
Most helpful comment
When you click the button, Chosen is receiving the
chosen:open
event. However, the event continues to bubble up the DOM and Chosen is immediately detecting a click on an element that is not the active Chosen ... so it closes it. Make sense?If you are working with inline JS, the easiest solution is to use
setTimeout
to break out of the current event stack:You almost certainly shouldn't be using inline JS, though. You can still use
setTimeout
if you want, but just stopping the event bubbling should be good enough.I've updated your fiddle with this working code: http://jsfiddle.net/EArg6/33/