猿问

如何在 Microsoft Edge 中获取选定单选按钮的值?

我需要从一组单选按钮中获取所选单选按钮的值,以下代码适用于 chrome。我可以在输入上使用 value 属性,但是在 Edge 和 IE 上,myRadio 上没有 value 属性。


是否有一个不错的跨浏览器替代方法来使用纯 javascript 获取所选单选按钮的值?


function test(){

  //prints selected button's value on chrome while undefined on Edge

  console.log(document.getElementById("myForm").myRadio.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>


德玛西亚99
浏览 161回答 3
3回答

POPMUISE

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

www说

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

慕雪6442864

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: input1: input2: inputlength: 3value: "1"您可以尝试使用 :checkedconsole.log(document.querySelector('input[name="myRadio"]:checked').value);
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答