Javascript如何获取radio选中后的值?

2016-05-16 21:44 阅读 8 次 评论关闭

刚刚猎微网分享了2种JS获取select下拉框选中的值,详情请看《两种Javascript获取select下拉框选中的值的方法》这篇文章。那么如果是想通过JS获取radio选中的值呢?具体实现方法如下:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>text</title>
<script>
var chk = 0;
window.onload=function (){
var chkObjs = document.getElementsByName("radio");
for(var i=0;i<chkObjs.length;i++){
if(chkObjs[i].checked){
chk = i;
break;
}
}
}
function check_radio(){
var chkObjs = document.getElementsByName("radio");
for(var i=0;i<chkObjs.length;i++){
if(chkObjs[i].checked){
if(chk == i){
alert("radio值没有改变不能提交");
break;
}
}
}
}
</script>
</head>

<body>
<form action='' method='post' onsubmit='javascript:return check_radio()'>
<input type='radio' value='1' name='radio' checked='checked'>一;
<input type='radio' value='2' name='radio'>二;
<input type='radio' value='3' name='radio'>三;
<input type='radio' value='4' name='radio'>四;
<input type='radio' value='5' name='radio'>五;

<input type=submit value=sub >
</form>
</body>
</html>
=============================================
另外,如果使用.net控件,仍然可以使用JS获取选中值,如:
<asp:RadioButtonList ID="rblID" runat="server" RepeatColumns="7" RepeatLayout="Flow">
<asp:ListItem Value="1" Selected="True">选项一</asp:ListItem>
<asp:ListItem Value="2">选项二</asp:ListItem>
<asp:ListItem Value="3">选项三</asp:ListItem>
</asp:RadioButtonList>

注意各选项radio.ID的html生成规则分别为:rblID_0、rblID_1、rblID_2。即等同于:
<input id="rblID_0" type="radio" name="rblID" value="1" checked="checked" />
<input id="rblID_1" type="radio" name="rblID" value="2" />
<input id="rblID_2" type="radio" name="rblID" value="3" />

版权声明:本文著作权归原作者所有,欢迎分享本文,谢谢支持!
转载请注明:Javascript如何获取radio选中后的值? | 猎微网

评论已关闭!