2 回答
TA贡献1788条经验 获得超4个赞
var radios = document.getElementsByName('genderS');
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
// do whatever you want with the checked radio
alert(radios[i].value);
// only one radio can be logically checked, don't check the rest
break;
}
}
<label for="gender">Gender: </label>
<input type="radio" name="genderS" value="1" checked="checked">Male</input>
<input type="radio" name="genderS" value="0" >Female</input>
TA贡献1821条经验 获得超4个赞
您提供的代码段应该可以工作。它确实假设 HTML 中有输入字段:
有
name="choice"
,并且已被检查
没有看到 HTML,很难说,但可能会在 HTML 中查找拼写错误。
document.getElementById('button').addEventListener('click', () => {
const radio = document.querySelector('input[name="choice"]:checked');
if (radio) {
const answer = radio.value;
console.log(`choice ${answer}`);
} else {
console.log('no choice');
}
});
<label><input type="radio" name="choice" value="1" /> One</label>
<label><input type="radio" name="choice" value="2" /> Two</label>
<div>
<button id="button">Click</button>
</div>
添加回答
举报