Tip - Fetching Radio Button Value

It is common task to find a checked radiobutton element and fetch its value.
It's easy to fetch value of element with known ID, but when you have many radio buttons checking each of the known IDs is at least impractical. One could get document.getElementsByName() but then it is possible that some other elements with the same name were returned, so it still needs additional filtering. There are of course thousands of ways to fetch checked radio button value but with Prototype it is very easy, clean, and can by consistently incorporated into Prototype's Form object.

This simple function adds a method #getCheckedRadioValue(name) to Form elements:

   getCheckedRadioValue: function (formElement, name) {
     formElement = $(formElement);
     var checkedElement = formElement
       .select('input[name='+name+'][type=radio]') //gather all radio inputs with provided /name/
       .find(function(inputElem){ return inputElem.checked;}); //find first checked element
     if (checkedElement) {
       return checkedElement.getValue(); //return iths value if found
     } else {
       return null;
   }//end of getCheckedRadioValue

The function selects all the radio inputs of the form with the provided name. Then it tries to find the checked one. If there is any checked radio button, it's value is returned.

Now all you need to do is to call $('formId').getCheckedRadioValue('nameOfRadioButtons') to fetch value of selected radio button.
Here you can find a working demo.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License