JavaScript如何正确读取Radio的值

     Radio 是 HTML 中的单选框,同一个 form 中,name 相同的 Radio 构成一组,这一组中最多只允许有一个 Radio 被选中。

     如果将 form 提交到服务器端 ASP 程序,ASP 程序要获得用户选择的那个 Radio 的 value 是非常方便的,用 request.Form("RadioName"),不必理会有几个 Radio。

     但在 JS(JavaScript) 中就要复杂多了,我们不能像对其它元素(如:文本框)一样,使用 formid.objName.value 来取值,我们应该循环这个组的 Radio,判断其 checked 属性,再取值。


 

<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>读取 Radio 的值</title>
</head>

<body>

<form id="form1" action="" method="">
    
<div><input type="radio" name="r" id="r1" value="一"><label for="r1">选项一</label></div>
    
<div><input type="radio" name="r" id="r2" value="二"><label for="r2">选项二</label></div>
    
<div><input type="radio" name="r" id="r3" value="三"><label for="r3">选项三</label></div>
    
<div><input type="button" value="检查选择项" onclick="javascript:Foo();"></div>
</form>

<script type="text/javascript" language="javascript">
<!--
function Foo()
{
    
var selectedIndex = -1;
    
var form1 = document.getElementById("form1");
    
var i = 0;
    
    
for (i=0; i<form1.r.length; i++)
    
{
        
if (form1.r[i].checked)
        
{
            selectedIndex 
= i;
            alert(
"您选择项的 value 是:" + form1.r[i].value);
            
break;
        }

    }

    
    
if (selectedIndex < 0)
    
{
        alert(
"您没有选择任何项");
    }

}

-->
</script>

</body>

</html>

 

     阿磊记:

          其中 获取form 这步很重要,一定要通过document.getElementById 取得,如果直接使用document.form1貌似后面的radiobox 没有办法取得 实在搞不懂为什么

posted on 2008-08-31 16:28  Play灬IT  阅读(4712)  评论(0编辑  收藏  举报

导航