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

How to get selected radio button's value in Microsoft edge?

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

是否有一个很好的跨浏览器替代方案来使用普通 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>

只是select唯一一个有属性"checked":

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>

我认为 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>

Edge returns 似乎是一个 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>

Chrome

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

您可以尝试使用以下方法:

方法一:使用document.querySelector()方法:

    function test() {
        //prints selected button's value on chrome while undefined on Edge
        console.log(document.querySelector("input[name = 'myRadio']:checked").value);
    }

方法二:使用document.getElementsByName()方法获取电台列表,然后查看选中的是哪个电台:

    function test() {
        //prints selected button's value on chrome while undefined on Edge

        var radioes = document.getElementsByName('myRadio');
        var selectedvalue;
        for (var i = 0; i < radioes.length; i++) {
            if (radioes[i].checked) {
                selectedvalue = radioes[i].value;
            }
        }
        console.log(selectedvalue);
    }

方法三:添加JQuery引用,使用JQuery选择器获取选中的值:

JQuery参考:

 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Javascript方法:

    function test() {
        //prints selected button's value on chrome while undefined on Edge

        console.log($("input:radio[name='myRadio']:checked").val());
    }