Kevin Kloet Kevin Kloet -4 years ago 116
Javascript Question

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

i have noticed that the event for

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=""></script>
<span for="firstId">number: </span>
<input type="number" id="firstId"/>
<button id="randomButton">Get a random number</button><br>

Answer Source

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();


$('#firstId').val(Math.floor(Math.random()*2147483647 )+1).trigger('change');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download