---
title: "使用Prototype得到单选框组的值"
author: "夜鸣猪"
date: "2009-11-26T16:46:42Z"
tags: []
categories: ["Web前端"]
slug: "prototype"
draft: false
lastmod: "2009-11-26T16:47:12Z"
id: 528320
url: "https://hlee.iteye.com/blog/528320"
---

Using Prototype Javascript to get the value of a radio group

怎么样得到单选框组的vlaue呢，下面是一个例子：

```js
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;
    }
}
```

我们的prototype代码需要知道form和单选框组的名字（radio group name）

```js

/**
* 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;
}

```

在使用的时候，你需要传入一个form的对象或者id和单选框组的名字或者单选框的id，如下：

```js

var value = $RF('radio_btn_id');
var value = $RF('form_id', 'radio_grp_name');

```