March 1st, 2007 Using Prototype Javascript to get the value of a radio group

I am constantly asked how to find the value of the selected radio button in a radio group. The way I usually told people was something like this:

var radioGrp = document['forms']['form_name_or_id']['radio_grp_name'];
for(i=0; i < radioGrp.length; i++){
    if (radioGrp[i].checked == true) {
        var radioValue = radioGrp[i].value;
    }
}
 

To use it you need a reference to the radio group (not just a single button), which means you need to know the form, and the radio group name. Since I use prototype for almost everything now, I decided to use it to make a simple function for this purpose. First of all, here is 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');
 

Hopefully this will help simplify things for someone. Maybe they will eventually add something similar into prototype itself.

See also: Using Prototype Javascript to set the value of a radio group

26 Responses to “Using Prototype Javascript to get the value of a radio group”

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Search