Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

val() doesn't trigger change() in jQuery

I'm trying to trigger the change event on a text box when I change its value with a button, but it doesn't work. Check this fiddle.

If you type something in the text boxes and click somewhere else, change is triggered. However, if you click the button, the text box value is changed, but change doesn't trigger. Why?

like image 595
Ergec Avatar asked Jul 05 '10 12:07

Ergec


People also ask

Does jQuery Val trigger change?

When you dynamically set a value in a textfield using jQuery . val(), you have to manually trigger the . change event if you want to add extra code that trigger when the value of the field change.

What does val () in jQuery do?

val() method is primarily used to get the values of form elements such as input , select and textarea . When called on an empty collection, it returns undefined .

What is trigger change in jQuery?

jQuery trigger() Method The trigger() method triggers the specified event and the default behavior of an event (like form submission) for the selected elements. This method is similar to the triggerHandler() method, except that triggerHandler() does not trigger the default behavior of the event.

How do I create a trigger drop change event?

$(document). ready(function(){ $('#countrylist'). change(function(e){ // Your event handler }); // And now fire change event when the DOM is ready $('#countrylist'). trigger('change'); });


2 Answers

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").val( 777 ).change(); // someObject.onchange(); in standard JS 

Alternatively, you can trigger the event using:

$("#mytext").val( 777 ).trigger("change"); 
like image 153
djdd87 Avatar answered Sep 18 '22 18:09

djdd87


From redsquare's excellent suggestion, this works nicely:

$.fn.changeVal = function (v) {     return this.val(v).trigger("change"); }  $("#my-input").changeVal("Tyrannosaurus Rex"); 
like image 42
Chris Fulstow Avatar answered Sep 17 '22 18:09

Chris Fulstow