Skip to content

Instantly share code, notes, and snippets.

@kflorence
Created January 8, 2011 02:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kflorence/770449 to your computer and use it in GitHub Desktop.
Save kflorence/770449 to your computer and use it in GitHub Desktop.
Fix for IE not firing the change event for certain inputs (namely, checkboxes and multiple select lists).
/**
* Fixes binding the "change" event to checkboxes and select[type=multiple]
* for Internet Explorer.
*
* @param {jQuery|Element|Element[]} elements
* The DOM Element we wish to bind the event to.
*
* @param {String} eventType
* The name of the event we want to bind to.
*
* @param {function} callback
* The function to execute when the event is triggered
*/
var bind = function(elements, eventType, callback) {
var $elements = $(elements),
rValidProps = /^(checked|selectedIndex)$/,
hasPropertyChange = ("onpropertychange" in document.body);
if (!$elements.length || typeof eventType !== "string") {
return $elements;
}
if (eventType !== "change") {
return $elements.bind(eventType, callback);
}
$elements.each(function() {
eventType = hasPropertyChange && (this.type === "checkbox" || this.tagName.toLowerCase() === "select" && this.multiple) ? "propertychange" : "change";
$(this).bind(eventType, function(e) {
if (e.type !== "propertychange" || rValidProps.test(window.event.propertyName)) {
callback.call(this, e);
}
});
});
};
@kflorence
Copy link
Author

@kflorence
Copy link
Author

Note: this seems to have been fixed in jQuery version 1.4.2, although select[multiple] elements still seem to be acting funny (it only fires every other change for some reason).

@kflorence
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment