Skip to content

Instantly share code, notes, and snippets.

@bensochar
Last active August 29, 2015 13:56
Show Gist options
  • Save bensochar/9220093 to your computer and use it in GitHub Desktop.
Save bensochar/9220093 to your computer and use it in GitHub Desktop.
jQuery to detect checkbox change on older browsers. Uses a conditional class on the html tag.
jQuery(document).ready(function($) {
$('label :checkbox').checkedChange();
$('label :checkbox').wrapCheckboxInputs();
$('label :radio').radioChange();
});
(function($) {
$.fn.wrapRadioInputs = function() {
return this.each(function() {
var _label = $(this).closest("label.radio");
var _nme = this.name;
var _id = this.id;
$(this).wrap('<div class="box" data-id="' + _id + '"></div>').wrap('<div class="check" data-id="' + _id + '"></div>');
});
}
$.fn.radioChange = function(_class) {
_class = _class || "checked";
return this.each(function() {
var _label = $(this).closest("label.radio");
var _nme = this.name;
if (!navigator.userAgent.match(/MSIE/)) {
$(this).change(function() {
$('label[for="' + _nme + '"]').removeClass(_class);
$(this).is(":checked") ? _label.addClass(_class) : _label.removeClass(_class);
})
} else {
$(_label).click(function() {
$('label[for="' + _nme + '"]').removeClass(_class);
$(':radio', this).is(":checked") ? _label.addClass(_class) : _label.removeClass(_class);
})
}
$(this).focus(function() {
$(_label).addClass("focus");
});
$(this).blur(function() {
$(_label).removeClass("focus");
});
});
};
$.fn.wrapCheckboxInputs = function() {
return this.each(function() {
var _label = $(this).closest("label.checkbox");
var _nme = this.name;
var _id = this.id;
$(this).wrap('<div class="box" data-id="' + _id + '"></div>').wrap('<div class="check" data-id="' + _id + '"></div>');
});
}
$.fn.checkedChange = function(_class) {
_class = _class || "checked";
return this.each(function() {
var _label = $(this).closest("label.checkbox");
var _nme = this.name;
if (!navigator.userAgent.match(/MSIE/)) {
$(this).change(function() {
$(this).is(":checked") ? _label.addClass(_class) : _label.removeClass(_class);
});
} else {
$(this).click(function() {
$(this).is(":checked") ? _label.addClass(_class) : _label.removeClass(_class);
});
}
$(this).focus(function() {
$(_label).addClass("focus");
});
$(this).blur(function() {
$(_label).removeClass("focus");
});
});
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment