单选按钮可以像复选框按钮一样实现吗?我希望广播电台可以多选。不要使用复选框按钮!
我想要的效果如下:
[0,1,2]
function clickButton() {
var radios = document.getElementsByName('gender');
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
console.log(radios[i].value);
break;
}
}
}
<form id="Selection">
<input type="radio" name="gender" value="0" /> Male<br>
<input type="radio" name="gender" value="1" /> Female<br>
<input type="radio" name="gender" value="2" /> Other<br>
<button onclick="clickButton();return false;">submit</button>
</form>
答案 0 :(得分:0)
唯一允许这样做的方法是拥有唯一的名称。单选按钮专门用于单选。如果您想要多选功能,那么这就是复选框的用途。
<form id="Selection">
<input type="radio" name="gender_male" value="0" /> Male<br>
<input type="radio" name="gender_female" value="1" /> Female<br>
<input type="radio" name="gender_other" value="2" /> Other<br>
<button onclick="clickButton();return false;">submit</button>
</form>
答案 1 :(得分:0)
您可以为单选按钮指定不同的名称,然后按标签名称获取标签并将值推入数组。
PS :正确的方法是选中复选框,因为它们旨在执行此功能
工作演示
function clickButton() {
var radios = document.getElementsByTagName('input');
var checked = [];
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
checked.push(radios[i].value);
}
}
console.log(checked);
}
<form id="Selection">
<input type="radio" name="gender1" value="0" /> Male<br>
<input type="radio" name="gender2" value="1" /> Female<br>
<input type="radio" name="gender3" value="2" /> Other<br>
<button onclick="clickButton();return false;">submit</button>
</form>
答案 2 :(得分:0)
只需为您的单选按钮使用不同的名称-
function clickButton() {
var radios = document.getElementsByClassName('gender');
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
console.log(radios[i].value);
}
}
}
<form id="Selection">
<input type="radio" class="gender" name="genderMale" value="0" /> Male<br>
<input type="radio" class="gender" name="genderFemale" value="1" /> Female<br>
<input type="radio" class="gender" name="genderOther" value="2" /> Other<br>
<button onclick="clickButton();return false;">submit</button>
</form>