In JavaScript, how can I get all radio buttons in the page with a given name?

前端 未结 8 589
执笔经年
执笔经年 2020-12-03 11:14

Like the title says, what\'s the best way in JavaScript to get all radio buttons on a page with a given name? Ultimately I will use this to determine which specific radio b

相关标签:
8条回答
  • 2020-12-03 12:06
    <form name="myForm" id="myForm" action="">  
    <input type="radio" name="radioButton" value="c1">Choice 1
    <input type="radio" name="radioButton" value="c2">Choice 2
    </form>
    <script>
    var formElements = window.document.getElementById("myForm").elements;
    var formElement;
    var radioArray = [];
    
    for (var i = 0, j = 0; i < formElements.length; i++) {
        formElement = formElements.item(i);
        if (formElement.type === "radio" && formElement.name === "radioButton") {
            radioArray[j] = formElement;
            ++j;
        }
    }
    alert(radioArray[0].value);
    alert(radioArray[1].value);
    </script>
    
    0 讨论(0)
  • 2020-12-03 12:07

    getElementsByName didn't work for me. I did this:

        var radios = document.getElementsByTagName('input');
        for (i = 0; i < radios.length; i++) {
            if (radios[i].type == 'radio' && radios[i].checked) {
                nbchecked++;
            }
        }
    
    0 讨论(0)
提交回复
热议问题