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>
From jQuery trigger() docs
Any event handlers attached with .on() or one of its shortcut methods are triggered when the corresponding event occurs.
When you do
$("#notDisplayedSelect").val("3").trigger("change");
only handlers attached with on()
or change()
will be triggered.
Apparently, this does not include handlers attached with the native
addEventListener("change", function (e) {...});
If you want to trigger the handler attached by native javascript, you can do
var event = new CustomEvent("change");
document.getElementById("notDisplayedSelect").dispatchEvent(event);
Update Workaround for above in IE
var event = document.createEvent("HTMLEvents");
event.initEvent("change", true, true);
document.getElementById("notDisplayedSelect").dispatchEvent(event);
When you add a handler using jQuery, jQuery keeps information about this handler in its internal memory, in addition to adding it as a browser event listener. Then when you call trigger("change")
, it just calls these handlers itself, rather than going through the browser.
In the browser, it makes no sense to change an invisible element, because the change
event is associated with user interaction.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.