val() doesn't trigger change() in jQuery
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");
From redsquare's excellent suggestion, this works nicely:
$.fn.changeVal = function (v) {
return this.val(v).trigger("change");
}
$("#my-input").changeVal("Tyrannosaurus Rex");
You can very easily override the val
function to trigger change by replacing it with a proxy to the original val
function.
just add This code somewhere in your document (after loading jQuery)
(function($){
var originalVal = $.fn.val;
$.fn.val = function(){
var result =originalVal.apply(this,arguments);
if(arguments.length>0)
$(this).change(); // OR with custom event $(this).trigger('value-changed');
return result;
};
})(jQuery);
A working example: here
(Note that this will always trigger change
when val(new_val)
is called even if the value didn't actually changed.)
If you want to trigger change ONLY when the value actually changed, use this one:
//This will trigger "change" event when "val(new_val)" called
//with value different than the current one
(function($){
var originalVal = $.fn.val;
$.fn.val = function(){
var prev;
if(arguments.length>0){
prev = originalVal.apply(this,[]);
}
var result =originalVal.apply(this,arguments);
if(arguments.length>0 && prev!=originalVal.apply(this,[]))
$(this).change(); // OR with custom event $(this).trigger('value-changed')
return result;
};
})(jQuery);
Live example for that: http://jsfiddle.net/5fSmx/1/