0

I would like an alternative to using callback method inside of jQuery's .val() method (Which it clearly doesn't support). For example:

http://jsbin.com/ilahan/edit#source

$("#box").val("The New Value", function(){
  alert("It's changed now");
});
Michael Jasper
  • 7,962
  • 4
  • 40
  • 60

3 Answers3

4

What's wrong with using .change ?

$("#box").val("The New Value").change(function(){
  alert("It's changed now");
});

As Vega stated in his comments, changing the val from code won't trigger the change event no matter what: .val() doesn't trigger .change() in jquery

Community
  • 1
  • 1
Miroslav Popovic
  • 12,100
  • 2
  • 35
  • 47
  • What does this code do? change the value and register a handler? – Selvakumar Arumugam Jun 15 '12 at 19:59
  • if you chained then in the opposite order you'd even have a handler for the change event when you are setting the value – Rune FS Jun 15 '12 at 19:59
  • @RuneFS even still it doesn't make any sense to add a handler for this question. – Selvakumar Arumugam Jun 15 '12 at 20:01
  • @Vega did I ever claim it did? – Rune FS Jun 15 '12 at 20:02
  • @RuneFS Can you tell me what _you'd even have a handler for the change event when you are setting the value_ means? – Selvakumar Arumugam Jun 15 '12 at 20:03
  • @Vega, you're right... The question seems to be a little odd. I just wanted to point out that .change should be used for callback, not the val() itself. Chaining the calls is just a syntactical sugar. – Miroslav Popovic Jun 15 '12 at 20:04
  • @MiroslavPopovic I was just trying to say that even after registering `.change`, When updating value via script such as `.val` will not trigger the `.change`. Probably you should mention that and add a `.change()` call at the end of `.val()`. guess I am just being picky. – Selvakumar Arumugam Jun 15 '12 at 20:05
  • @vega that if the code was .change(...).val(...) the call to val would fire the change event and there'd be an event handler to handler that event. Does it make sense? well that depends if you need the event handler or you simply need to execute some code this one time – Rune FS Jun 15 '12 at 20:07
  • I just edited my answer... Wasn't aware that val() doesn't trigger the change event. Thanks @Vega :) – Miroslav Popovic Jun 15 '12 at 20:09
3

.val is an instant change and so there is no need for callback? Why do you need such a callback?

Below code should do the same as what you wanted from a callback on .val

$("#box").val("The New Value");
alert("It's changed now");
Selvakumar Arumugam
  • 79,297
  • 15
  • 120
  • 134
1

Theres no need to do a call back when setting the value, as the change happens immediately. If you are looking to execute code when the field value changes, you can use:

$("#box").change(function(){
    alert('value changed');
});
Jason Kulatunga
  • 5,814
  • 1
  • 26
  • 50