Prasad Bolla's SharePoint Blog

Click Here to go through the Interesting posts within my Blog.

Click Here to go through the new posts in my blog.

Monday, December 05, 2011

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:
1
var radioGrp = document['forms']['form_name_or_id']['radio_grp_name'];
2
for(i=0; i < radioGrp.length; i++){

3
    if (radioGrp[i].checked == true) {
4
        var radioValue = radioGrp[i].value;

5
    }
6
}
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:
01
/**
02
* Returns the value of the selected radio button in the radio group, null if

03
* none are selected, and false if the button group doesn't exist
04
*

05
* @param {radio Object} or {radio id} el
06
* OR

07
* @param {form Object} or {form id} el
08
* @param {radio group name} radioGroup

09
*/
10
function $RF(el, radioGroup) {

11
    if($(el).type && $(el).type.toLowerCase() == 'radio') {
12
        var radioGroup = $(el).name;

13
        var el = $(el).form;
14
    } else if ($(el).tagName.toLowerCase() != 'form') {

15
        return false;
16
    }

17

18
    var checked = $(el).getInputs('radio', radioGroup).find(

19
        function(re) {return re.checked;}
20
    );

21
    return (checked) ? $F(checked) : null;
22
}
You can pass it either a form (object or id) and a radio group name, or a radio button (object or id).
1
var value = $RF('radio_btn_id');
2
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.

No comments:

Post a Comment