Created
January 23, 2012 10:26
-
-
Save kirel/1662367 to your computer and use it in GitHub Desktop.
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
/* 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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Fork: Fix setting of 'for' attribute of label element for IE (IE was excited to loop around when seeing the for (non-)keyword)