I am seeing a weird behavior that when I use addEventListener
, change
event handler doesn't get fired on the select with display: none;
. On the other hand, when I use jQuery, it does fire. What's the trick that allows jQuery to do that and how do I make it work in plain JavaScript?
Here is code that shows the example.
// This doesn't work
document.getElementById("notDisplayedSelect").addEventListener("change", function(e) {
$("#output").text("When select is hidden events still fire: new value = " + $(this).val());
});
/*
// This works
$("#notDisplayedSelect").change(function (e) {
$("#output").text("When select is hidden events still fire: new value = "+ $( this ).val());
});
*/
$("#setValue").click(function() {
$("#notDisplayedSelect").val("3").trigger("change");
});
#notDisplayedSelect {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<select id="notDisplayedSelect">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<span id="output">I show selected value</span>
<button id="setValue">Select third option in the hidden select</button>