views:

66

answers:

3

Hello, I am trying to trigger .change() on a text box when I change it's value simply with a button but it doesn't work. Check link below. If you type something in textbox then click somewhere else .change() triggers but if you click only button, it changes textbox value but .change() doesn't trigger.

:( why?

http://jsbin.com/otove/edit

+3  A: 

onchange only fires when the user types into the input and then the input loses focus.

You can manually call the onchange event using after setting the value:

$("#mytext").change(); // someObject.onchange(); in standard JS

Alternatively, you can trigger the event using:

$("#mytext").trigger("change");
GenericTypeTea
Is there a reason that jQuery guys didn't implement this?
Ergec
Didn't implement what?
GenericTypeTea
feel free to extend jquery and add a say valWithChange function that will do what you want. It cannot be the default action as many times you do not want the event triggering from an automated value change, only when a user interacts with the element
redsquare
@redsquare good idea.
GenericTypeTea
+2  A: 

No you might need to trigger it manually after setting the value:

$('#mytext').change();

or:

$('#mytext').trigger('change');
Darin Dimitrov
A: 

It looks like the events are not bubbling. Try this:

$("#mybutton").click(function(){
  var oldval=$("#mytext").val();
  $("#mytext").val('Changed by button');
  var newval=$("#mytext").val();
  if (newval != oldval) {
    $("#mytext").trigger('change');
  }
});

I hope this helps.

I tried just a plain old $("#mytext").trigger('change') without saving the old value, and the .change fires even if the value didn't change. That is why I saved the previous value and called $("#mytext").trigger('change') only if it changes.

Jay Godse