这是我的代码:
<script>
function myFunction() {
var x;
x = document.getElementById("numb2").value;
document.write(x);
}
</script>
***
<body>
<form>
<input id = "numb2" value = "Male" type="radio">Male
<input id = "numb2" value= "Female" type="radio">Female
</form>
</body>
问题在于,无论我选择什么,我都会得到“男性”。
答案 0 :(得分:1)
首先,您需要通过为两个按钮提供相同的name
来创建按钮组。然后,您可以使用querySelector
选择所选元素并获取其值。
function myFunction() {
var val = document.querySelector("[name=numb2]:checked").value;
document.getElementById("output").innerHTML = val;
}
document.getElementById("button").addEventListener("click", myFunction);
<input name = "numb2" value = "Male" type="radio">Male
<input name = "numb2" value = "Female" type="radio">Female
<div>
Chosen: <span id="output"></span>
</div>
<button id="button">Click</button>
答案 1 :(得分:1)
检查fiddle:
<form>
<input name='sex' value = "Male" type="radio">Male
<input name='sex' value= "Female" type="radio">Female
</form>
您必须使用name属性来实现此功能,并遍历所有元素以检查选择了哪个无线电元素,如下面的代码所示。
function myFunction() {
var value = "NONE";
var elems = document.getElementsByName("sex");
for(var i = 0; i < elems.length; i++) {
if(elems[i].checked) {
value = elems[i].value;
break;
}
}
alert(value);
}
答案 2 :(得分:0)
首先你必须在组中添加单选按钮,你可以使用属性&#34; name&#34;来完成。让我告诉你如何做到这一点。
<input type="radio" name="groupRadio" value="male">Male
<input type="radio" name="groupRadio" value="female">Female