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.

43 thoughts on “Using Prototype Javascript to get the value of a radio group

  1. Thank you so much for this! I was using Smarty, which automatically names radio button groups with the same id… This saved my butt.

  2. Very slick little utility function.

    I have been fiddling around with using prototype to retrieve the selected value of a group of radio buttons.

    But I was always getting js errors surrounding prototype coming back in Firebug.

    (Such things as “Form has no properties=> var inputs = form.getElementsByTagName(‘input’);” when running the following in the Console: Form.getInputs(‘radio’);)…

    I put your code into place and am seeing “$(el).getInputs is not a function” as the error I’m getting now.

    I’m hoping that they’re related problems that I’m having and that you may have seen something similar before.

    Thanks!

  3. Scott: That works, as long as you have the form id and the name of the radio group. This way works with that, as well as with just an id of any radio button in the group.

    Rebma: So you are passing it either a reference to a specific radio button, or a unique id for one of the radio buttons in the group?

  4. I’m actually looking a bit closer at the XML/XSL output and I’m seeing that the HTML generated has all 3 of my radio buttons with the same id. They end up being generated as follows:

    And I’m executing: $RF(‘xyz’,’xyz’);

    I’m assuming it’s the non-unique ids…

  5. oops… my examples of generated radio buttons were removed.

    Well, they were all of id ‘xyz’ and name ‘xyz’.

    Thanks!

  6. Rebma: Since the ids are not unique (which they should be by definition), it might not work to supply a radio id. Try supplying a form id, and the name of the radio group:
    $RF(‘form_id’, ‘xyz’);

  7. This is good, but I had a problem using it with some radio buttons that were not contained in a form. Here’s the function I used to get it to work:

    //——————-
    function $RF(reid) {
    return $$(‘input[type=radio][name=’ $(reid).name ‘]’).find(function(el) { return el.checked }).value;
    }
    //——————-

    Hopefully that will be legible after wrapping…

  8. As [tofuTnT] says, the function needs a little adjustment. An intermediate step must be added before using the $F() function. The way I did it was the following:


    var res = $(el).getInputs('radio', radioGroup).find(function(re) {return re.checked;});
    if(res != null) {
    return $F(res);
    } else {
    return ""
    }

    There is probably a much more elegant way of doing that, but I’m a simple person.

    Oh, I also changed the function to return “” instead of false when parameter el is not a form. This way I only get strings as results. Makes more sense to me to get always the same data type.

    Great function, any way. I added it to my code with the proper credits.

  9. I realized that I haven’t updated this in a while. I had made a couple minor changes. First, if no radio button is selected, it returns null. Also, if you pass bad parameters, it returns false, rather than giving an error.

  10. But how to *set* radio group value and selected button in prototype?

    In other words, I’m looking for the prototype equivalent for jQuery’s…

    $("#some_radio_group").val("myDefaultValue");
    $("#some_radio_group_member1").attr("checked", "checked");

    Probably (?) easy; I just started using prototype two days ago, and haven’t figured this one out yet :). Thanks for any insights.

  11. Sorry, I was on vacation. Here are solutions similar to yours:

    $$("input[type=radio][name='radioGroupName'][value='yourDefaultValue']").writeAttribute("checked", "checked");
    $("someRadioGroupMember").writeAttribute("checked", "checked");

  12. I have been getting an error stating getElementById() is an invalid method or propertie of this object/element when trying to retrieve a single input element of type RADIO with its ID…

    I am attempting to create an array of all radio box groups in a form by there name. WITHOUT having a name or ID..

    I am itterating throught all elements in form. If there type == radio I assign curEl.getAttribute(“name”) to myArray[curPos]

    see below

    function validate(theForm)
    {
    var errorCount = 0;
    var allErrors = "";

    // THIS ARRAY WILL BE USED FOR GROUPS OF RADIO ELEMENTS FROM FORM
    //CATAGORIZED BY NAME
    var radioGroups = new Array();
    //var radioGroups2 = new Array();

    for (i=0; i<theForm.elements.length; ++i)
    {
    var curInput = theForm.elements[i];
    //##########################################
    // GROUP RADIO ELEMENTS FOR LATER PROCESSING #
    // #
    // WHAT I AM TRYING TO DO #
    // CHECK ALL RADIO BOXES, WITHOUT FIRST KNOWING THE #
    // NAME OF THE RADIO BOX.. MODULARIZING THE CODE TO #
    // WORK WITH ANY FORM #
    //#########################################
    if (curInput.type =="radio")
    {
    //#######################################
    // INITIAL READ AND ARRAY ASSIGNMENT/INSTANTIATION #
    //######################################
    if (radioGroups.length == 0)
    {
    radioGroups[0] = curInput.getAttribute("name");
    }
    //########################################
    // ARRAYS HAVE BEAN INSTANTIATED, ADD PROCEEDING #
    // GROUP NAMES FOR LATER #
    // PROCESSING #
    //######################################
    else
    {
    var found = "false";
    for (i=0; i<radioGroups.length; ++i)
    {
    if (radioGroups[i]== curInput.getAttribute("name"))
    {
    found = "true";
    i = radioGroups.length;
    }
    }
    if (found == "false")
    {
    radioGroups[radioGroups.length] = curInput.getAttribute("name");
    }

    }
    }
    }

    this holds up processing times out, and I can’t see why it would be a never ending loop..

    Is there a problem with using radioGroups.length to reset the radio groups array? I am going to try and use a holding object for radioGroups.length see if that dose the trick.

  13. Well, this post was about using prototype, I’ll show you how quickly you can do this in prototype. To get all the input elements whose type is radio:
    $$('input[type="radio"]');
    If you want the names and not the actual elements, you can do this:
    $$('input[type="radio"]').pluck('name');
    If you want only unique names (so each group rather than each element):
    $$('input[type="radio"]').pluck('name').uniq();

  14. Hi Aaron, thanks for the great tips, could you please tell me how to get the selected value of each group of the radio button then?

  15. using prototype js
    if you have a group of radio button with a name says “color”, the following will return the checked value of this group

    $$(‘input:checked[type=”radio”][name=”color”]’).pluck(‘value’)

  16. I edited it a little so you can also set the value of the group:

    (I also removed the second attribute, I just give the first radio in the group an ID, and that’s how i reference them)

    function $RG(id) {
    id = $(id);
    var ret = new Object();

    var groupName = id.name;
    var form = id.form;

    ret.radios = form.getInputs(‘radio’, groupName);

    ret.getValue = function() {
    var elt = this.radios.find(function(re) {return re.checked;});
    return elt ? $F(elt) : null;
    };

    ret.setValue = function(value) {
    var elt = this.radios.find(function(re) {return re.value == value});
    if(elt) elt.checked = true;
    }

    return ret;
    }

  17. i tried to use what Jun Wan said, but it didn’t work.
    i used this instead, somewhat similar:
    myradiogroup = $$(‘input[type=”radio”][name=”myradiogroup”]’).find(
    function(re) {return re.checked;} ).value;

  18. I'm modifying a script that I've inherited, which uses your $RF function. The function doesn't pass the jslint.com test because you're declaring vars that have already been defined as parameters in the function signature (el, radioGroup).

    Any chance you could run the function through jslint.com and get it to pass? Thanks in anticipation.

    Tim

  19. Hello!

    Thanks for writing about this topic. I ran accross this radio button problem today and found Jun Wan’s solution (see some comments above) useful, and by the way, it works with the current prototype version:

    $$(’input:checked[type=”radio”][name=”color”]‘).pluck(’value’)

  20. Hi anyone, that’s what I’m looking for .
    But where is $F function, to complete the resource published by Aaron ?
    Thanks for any help.

Leave a Reply

Your email address will not be published. Required fields are marked *