Created
January 8, 2011 02:11
-
-
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).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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); | |
} | |
}); | |
}); | |
}; |
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).
Related tickets: http://bugs.jquery.com/ticket/4659 and http://bugs.jquery.com/ticket/1360
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Demo: http://www.jsfiddle.net/kflorence/mMjp6/