Changing an event triggers a jquery handler but not a javascript handler

I see a strange behavior that when I use addEventListener, the event handler changedoes not start when selected with display: none;. On the other hand, when I use jQuery, it fires. What trick allows jQuery to do this and how to make it work in regular JavaScript?

Here is the code that shows an 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>
Run codeHide result
+4
source share
2 answers

From jQuery trigger () docs

Any event handlers attached using .on () or one of its quick access methods are fired when the corresponding event occurs.

When you do

 $("#notDisplayedSelect").val("3").trigger("change");

, on() change().

-, ,

addEventListener("change", function (e) {...});

, javascript,

var event = new CustomEvent("change");
document.getElementById("notDisplayedSelect").dispatchEvent(event);

IE

var event = document.createEvent("HTMLEvents");
event.initEvent("change", true, true);
document.getElementById("notDisplayedSelect").dispatchEvent(event);

DEMO

JavaScript?

+2

jQuery, jQuery , . , trigger("change"), , .

, change .

0

Source: https://habr.com/ru/post/1589518/


All Articles