3 回答

TA贡献1765条经验 获得超5个赞
只需选择具有“已检查”属性的唯一一个:
function test(){
//prints selected button's value on chrome while undefined on Edge
console.log(document.querySelector('input[name="myRadio"]:checked').value);
}
<form id="myForm">
<input type="radio" name="myRadio" value="0" />
<input type="radio" name="myRadio" value="1" />
<input type="radio" name="myRadio" value="2" />
</form>
<button onClick="test()">Test</button>

TA贡献1775条经验 获得超8个赞
我认为 queryselector 应该可以在所有浏览器中正常工作。
function test(){
//prints selected button's value on chrome while undefined on Edge
console.log(document.querySelector('#myForm input[name="myRadio"]:checked').value);
}
<form id="myForm">
<input type="radio" name="myRadio" value="0" />
<input type="radio" name="myRadio" value="1" />
<input type="radio" name="myRadio" value="2" />
</form>
<button onClick="test()">Test</button>

TA贡献1812条经验 获得超5个赞
Edge 似乎返回 HtmlCollection 而不是 RadioNodeList。
document.getElementById("myForm").myRadio 的结果在:
边缘
HtmlCollection length="3">
<input name="myRadio" type="radio" value="0"></input>
<input name="myRadio" type="radio" value="1"></input>
<input name="myRadio" type="radio" value="2"></input>
</HtmlCollection>
铬合金
RadioNodeList(3) [input, input, input, value: "1"]
0: input
1: input
2: input
length: 3
value: "1"
您可以尝试使用 :checked
console.log(document.querySelector('input[name="myRadio"]:checked').value);
添加回答
举报