4

When set value of input in JavaScript which event raised? I tried these event: (propertychange change keypress paste focus textInput input keyup keydown change). For example:

$('input').live/bind/on('which event', function() {
    //...
});
$('input')[0].value = "sd";
5
  • 1
    Are you perhaps looking for the change event? Commented Aug 27, 2013 at 12:28
  • Since you're doing it programatically, why not just run whatever function you need when setting the input's value? Commented Aug 27, 2013 at 12:28
  • 2
    No event is raised when you change the value programmatically (except propertychange, which is non-standard). Consider raising your own event after performing the change operation. Commented Aug 27, 2013 at 12:29
  • For those who wonder, that one was IE-only learn.microsoft.com/en-us/previous-versions/windows/… ; And even there is was deemed buggy due to inconsistent behavior between various controls etc. help.dottoro.com/ljufknus.php But apparently there was a DOMAttrModified that had broader support. Commented Aug 21 at 12:27
  • Meaning it worked in FFox and Opera at one point. That refers to the MutationEvent API developer.mozilla.org/en-US/docs/Web/API/MutationEvent which was later dropped too in favor or MutationObserver. Commented Aug 21 at 12:33

3 Answers 3

6

When you set the value programmatically no event will be raised. You can raise it yourself though:

$('input')[0].value = "sd";
$('input').first().trigger("change");

Or just using jQuery:

$('input').first().val("sd").trigger("change");
Sign up to request clarification or add additional context in comments.

2 Comments

why you don't use just .change() function, such as answer of @Deepak Biswal
It's the same. The change function without arguments is just a shorthand for .trigger("change"). I think using trigger makes it clearer what's going on (the change event is triggered on the element), but you can use whichever you find easier to read.
1

You can do something like this. You have to explicitly call change event.

$('input').val('New Value').change();

Comments

1

When a value is changed via a script the change event is not fired, if you want to run a handler then you can trigger the event manually

$('input').eq(0).val("sd").trigger('change');

Comments

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.