Skip to content

Instantly share code, notes, and snippets.

@ChristianPeters
Forked from kirel/jquery.radiofy.js
Created January 27, 2012 17:49
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 ChristianPeters/1689982 to your computer and use it in GitHub Desktop.
Save ChristianPeters/1689982 to your computer and use it in GitHub Desktop.
/* jQuery Radiofy
* ==============
* Turns a select into a hidden text input and
* a set of radio buttons that resemble the options.
* This is used to enable client_side_validations for radio buttons.
* ---
* Daniel Kirsch
* (c) 2012 Zweitag GmbH
*/
(function($){
$.fn.radiofy = function (opts) {
opts = $.extend({}, opts);
if (!this.is('select')) return;
this.replaceWith(function () {
var select = $(this);
var name = select.attr('name'), id = select.attr('id'), val = select.val();
var attributes = {}; $.each(this.attributes, function () { attributes[this.name] = this.value; });
var ul = $('<ul>');
var hidden = $('<input type="text">').attr(attributes).val(val).prependTo(ul).hide();
$(this).find('option').each(function (index) {
var option = $(this);
if (opts.skip_empty && option.val() == '') return; // skip empty option
var li = $('<li>').appendTo(ul);
var label = $('<label>').attr('for', 'radiofied_' + id + '_' + index).appendTo(li);
var radio = $('<input type="radio">').attr({id: 'radiofied_' + id + '_' + index, name: 'radiofied_' + name}).val($(this).val()).appendTo(label);
if (option.is(':selected')) radio.attr('checked', true);
radio.change(function () {
if (radio.is(':checked')) hidden.val(radio.val()).change().focusout();
});
label.append($('<span>').append($(this).text()));
});
return ul;
});
}
})(jQuery);
@ChristianPeters
Copy link
Author

Fork: Fix setting of 'for' attribute of label element for IE (IE was excited to loop around when seeing the for (non-)keyword)

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