JS 如何获取radio选中后的值及不选择取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>
<input type="radio" name="money" value="1" />美元
<input type="radio" name="money" value="2" />日元
<input type="radio" name="money" value="3" />欧元
原生JS方式:(原生DOM操作会把文本也当做一个节点,所以会有nextSibling)
代码如下:
var 美元 = document.getElementsByName("money")[0].nextSibling.nodeValue;
var 日元 = document.getElementsByName("money")[1].nextSibling.nodeValue;
var 欧元 = document.getElementsByName("money")[2].nextSibling.nodeValue;
$('input[name="money"]:checked').next('span').html();
<input type="radio" name="money" value="1" checked="checked" /><span>美元</span>
<input type="radio" name="money" value="2" /><span>日元</span>
<input type="radio" name="money" value="3" /><span>欧元</span>
<!--正常的情况下,创建复选框或者单选框会使用label将其链接,比如:-->
<input id="radio1" type="radio" name="money" value="1" /><label for="radio1">美元</label>
以下要选择的:
function radioValue(){
var radArr = document.getElementsByName("radiov");
var radValue = "";
//alert(radArr.length);
for(var i=0; i<radArr.length; i++){
//alert(radArr[i].checked+" "+radArr[i].name + " "+ radArr[i].value);
if(radArr[i].checked){
radValue = radArr[i].value;
}
}
if(radValue != null && radValue != ""){
alert(radValue);
}else{
alert("请选择");
}
}
<input type="button" value="测试radio中获取数据" onclick="radioValue();"/>