5

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>

3
  • 2
    I am sorry, what is not working? Commented Nov 11, 2016 at 13:53
  • You will have to manually fire necessary function after its updated from JS Commented Nov 11, 2016 at 13:53
  • 1
    @AniketSahrawat He means if I do $("#firstId").val('test') no event is fired Commented Nov 11, 2016 at 13:53

1 Answer 1

12

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');
Sign up to request clarification or add additional context in comments.

3 Comments

exactly what i was looking for, thanks for reminding me about the fact that event have to be triggered by user input
@KevinKloet: glad it helps :)
Thanks, really helped! For anyone using the better approach for input listening .on("input"), remember to do .trigger("input") instead :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.