Some coworkers and myself have run into some confusion using the val( val ) function of jQuery to set the value of a control, and finding that the control's onChange event does not fire.
First of all, onChange is implemented differently between Firefox and IE. In IE, onChange for a select box fires right as the value of the select is changed. Some say that this implementation is incorrect and that the onChange event is supposed to fire after the control looses focus. Firefox implements the event the other way. I've not checked the W3C specs to see which is correct, because frankly I don't care. What I do care about is that I have to deal with the inconsistency.
So taking the implementation into consideration, when you want to set the value of a control using $("myInput").val(newValue);, the onChange not firing makes sense. We're not using val to tell the form to set the value of the control and then make it loose focus. Perhaps onChange should have been named OnAfterChange instead, but that's besides the point.
To get the behavior we're looking for, set the value then fire the onChange event of the control, we have to call .change() after val( val ).
function setViajQuery() {
$("#myInput").val("1");
$("#myInput").change();
}
This gives us the behavior we're looking for.
We could easily wrap this in a function to use whenever we're expecting onChange to be fired:
function setValAndFireOnChange(jQueryObj, newVal) {
jQueryObj.val(newVal);
jQueryObj.change();
}
function setViajQuery() {
setValAndFireOnChange($("#myInput"), "1");
}
Alternatively, let's extend jQuery:
(function($) {
$.fn.valChange = function(newValue) {
return this.each(function() {
var obj = $(this);
obj.val(newValue);
obj.change();
});
};
})(jQuery);
The code is the same, but instead of the calling syntax being setValAndFireOnChange($("#myInput"), "1");, we can have the same effect gracefully:
$("#myInput").valChange("1");
The benefit of extending jQuery is that we can respect jQuery's chaining:
$("#myInput").valChange("1").css("background","blue");
cf32127f-90fb-4864-9c95-89b560d772d8|3|4.0