Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery on change/input not working when updating value via JS [duplicate]

I have noticed that the event for $('#firstId') is not firing when the change is done by the Javascript itself.

Why is this the case?

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>
like image 745
Kevin Kloet Avatar asked Nov 11 '16 13:11

Kevin Kloet


1 Answers

That is because all the events attached above via handler are triggered by user action and not via code. you can use .trigger() or .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');
like image 85
Milind Anantwar Avatar answered Sep 30 '22 09:09

Milind Anantwar