为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

德玛西亚99 2021-06-28 16:23:08
我需要从一组单选按钮中获取所选单选按钮的值,以下代码适用于 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>
查看完整描述

3 回答

?
POPMUISE

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>


查看完整回答
反对 回复 2021-07-08
?
www说

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>


查看完整回答
反对 回复 2021-07-08
?
慕雪6442864

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);


查看完整回答
反对 回复 2021-07-08
  • 3 回答
  • 0 关注
  • 160 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信