JQuery on change / input not working when updating value via JS

I noticed that the event for $('#firstId')does not fire when the change is executed by javascript itself.

why is that so?

Is there a way to still fire the event?

here is an example:

$('#firstId').on('change input paste', function(){
  console.log("this is the input event being fired");
});

$('#randomButton').on('click', function(){
  $('#firstId').val(Math.floor(Math.random()*2147483647 )+1);
  console.log("randomButton being fired");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span for="firstId">number: </span>
<input type="number" id="firstId"/>
<p>Or</p>
<button id="randomButton">Get a random number</button><br>
Run codeHide result
+4
source share
1 answer

This is because all events associated with the handler above are triggered by user action, not code. you can use .trigger()either .change()here to trigger the event:

$('#firstId').val(Math.floor(Math.random()*2147483647 )+1).change();

or

$('#firstId').val(Math.floor(Math.random()*2147483647 )+1).trigger('change');
+10
source

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


All Articles