Daniel M. Hendricks

Fetching Radio Button Group Value with Prototype

I shamelessly lifted this code from Aaron Campbell, however, I thought it was a useful example of retrieving the value of a radio button group with Prototype.

The function:

/**
* Returns the value of the selected radio button in the radio group, null if
* none are selected, and false if the button group doesn't exist
*
* @param {radio Object} or {radio id} el
* OR
* @param {form Object} or {form id} el
* @param {radio group name} radioGroup
*/
function $RF(el, radioGroup) {
    if($(el).type && $(el).type.toLowerCase() == 'radio') {
        var radioGroup = $(el).name;
        var el = $(el).form;
    } else if ($(el).tagName.toLowerCase() != 'form') {
        return false;
    }

    var checked = $(el).getInputs('radio', radioGroup).find(
        function(re) {return re.checked;}
    );
    return (checked) ? $F(checked) : null;
}

You can pass it either a form (object or id) and a radio group name, or a radio button (object or id).

var value = $RF('radio_btn_id');
var value = $RF('form_id', 'radio_grp_name');

Post a Comment

You must be logged in to post a comment.

Tip: Sign up for a free Gravatar to have a photo next to your comment! Your gravatar will follow you around when you post to blogs that support it, based on the e-mail address you use to post.