I regularly use the prototype javascript library in JavaScript development (in fact, FreeTextBox4 will use it). But I’ve found that the $F() function doesn’t work like I expect it to with radio buttons. $F() will return null if a radio is not checked and the value if it is checked. What I want it to do is figure out the value of the currently selected radio in the radio group (all with the same name). Since prototype doesn’t do it, I decided to write one to do it. It will return null if none of the radios are checked and it works using either the ID of one of the radios or the name of the group. Here it is
function getRadioValue(idOrName) { var value = null; var element = document.getElementById(idOrName); var radioGroupName = null; // if null, then the id must be the radio group name if (element == null) { radioGroupName = idOrName; } else { radioGroupName = element.name; } if (radioGroupName == null) { return null; } var radios = document.getElementsByTagName('input'); for (var i=0; i<radios.length; i++) { var input = radios[ i ]; if (input.type == 'radio' && input.name == radioGroupName && input.checked) { value = input.value; break; } } return value; }
wrong url for prototype, should be: http://prototype.conio.net/
Just wanted to say: Thanks for the code.
thx, that code saved my ass 😀
Thanks a lot, that code really helped!
hi
this is very very nice example to get id of the radio …..
i appriceate ur knowledge…
thank u!
Thanks for the code buddy 🙂
Hiya, just wanted you to know I found a neat little solution which worked perfectly for me.
http://stereointeractive.com/blog/2008/06/05/get-radio-button-value-using-prototype/
The snippet is as follows:
$$(‘input:checked[type="radio"][name="my_radio_group"]’).pluck(‘value’);
@Mike, that’s great! How JavaScript usage has evolved in the 2 years since I posted this…
Thank’s John,
great function.
Hey this is an awesome method. It really works. Appreciate your knowledge. Thanks !!