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
Zack Says:
Thank you so much for this! I was using Smarty, which automatically names radio button groups with the same id… This saved my butt.
Scott Says:
I use this method, too:
var typeValue = Form.getInputs(’myform’,'radio’,'type’).find(function(radio) { return radio.checked; }).value;
http://www.rexchung.com/2007/02/22/getting-radio-buttons-value-with-prototypejs/
Duncan Says:
Very, very nice. Solves a problem I had quite nicely. Thanks for sharing
Seal Says:
Thank you very much, very nice!
Rebma Says:
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!
Aaron D. Campbell Says:
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?
Rebma Says:
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…
Rebma Says:
oops… my examples of generated radio buttons were removed.
Well, they were all of id ‘xyz’ and name ‘xyz’.
Thanks!
Aaron D. Campbell Says:
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’);
Solomon Says:
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…
Antonie Potgieter Says:
Awesome! Thank you for providing this great function. It is especially useful when doing Ajax requests.
tofuTnT Says:
if none of radio is selected, this function $RF seems to fail.
mel Says:
great thanks! helped solve my problem
Paulo Sargaço Says:
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.
Aaron D. Campbell Says:
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.
Ville Walveranta Says:
This is very useful! Thanks!
Ville Walveranta Says:
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.
Aaron D. Campbell Says:
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”);
Andres Says:
Great function. i think it should be included in the next version of prototype
vrann Says:
I use it)
Richard Hart Says:
Great! Thanks for sharing.
Shawn S. Says:
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.
Aaron D. Campbell Says:
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();Jun Wan Says:
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?
Jun Wan Says:
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’)
amiuhle Says:
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;
}