Skip to content

Instantly share code, notes, and snippets.

@esson
Last active December 14, 2015 14:08
Show Gist options
  • Save esson/5098124 to your computer and use it in GitHub Desktop.
Save esson/5098124 to your computer and use it in GitHub Desktop.
jQuery Plugin. Set each radio button group to the first value.
/*
* jquery.radioDefault.js
* Sets the first radio button of each radio button group to checked.
*
* Version: 1.0
* Author: Martin Eriksson
*/
(function ($) {
$.fn.radioDefault = function () {
return this.each(function () {
var context = this,
names = {};
// Collect all names.
//
$(':radio', context).each(function () {
if (this.name) {
names[this.name] = true;
}
});
// Iterate all names, get the first value, then set the value to the radio group.
//
$.each(names, function (key) {
if (key) {
var selector = ':radio[name="' + key + '"]',
value = $(selector, context).not(':disabled').first().val();
$(selector, context).val([value]).trigger('change');
}
});
});
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment