3

I can setup this listener:

$('input[type="text"]').on('keyup paste input change', function() {
  console.log('Hello!');
});

If I open DevTools and do:

$('input[type="text"]').val('a new value');

None of the events above are called. Which event should I listen for this cases?

3
  • Why don't you just trigger the callback handler manually by JavaScript? Commented May 11, 2013 at 20:46
  • 6
    .val() doesn't trigger any event. Commented May 11, 2013 at 20:46
  • 3
    $('input[type="text"]').val('a new value').trigger('change'); Commented May 11, 2013 at 20:48

2 Answers 2

6

Changing an elements value programatically doesn't trigger an event, you'll have to do that yourself. You could use trigger to trigger event handlers in jQuery :

$('input[type="text"]').val('a new value').trigger('change');
Sign up to request clarification or add additional context in comments.

Comments

-1

The .val() function is designed not to trigger events when executed. What I mean by that is even though it could technically have that functionality due to how jQuery works. If you use the .val() function you can manually execute the event you would like using $(element).val("something").click()/change()/input()/keyup()

2 Comments

The .val() function is designed not to trigger events when executed. That would imply there is code intentionally written to not trigger an event. That there is no event raised is nothing to do with .val() or jQuery at all. Programmatically changing the value using plain JavaScript also won't raise the change event.
I wasn't implying that at all. jQuery however could easily have been designed to implement this functionality. Now I was just stating that it does not do that, and you would need to handle it accordingly. I was specifically referring to jQuery which in its documentation for the .val() function does not specifically reference running through event execution or not.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.