Getting the value from a radio button using javascript

后端 未结 2 1912
走了就别回头了
走了就别回头了 2020-12-07 03:10

I have a HTML form with radio inputs and want to use javascript to analyse the results. I am getting stuck at retrieving the form information in my JavaScript function:

相关标签:
2条回答
  • 2020-12-07 03:26

    The object Nodelist that you're referring to is being returned because you have a group of elements that share the same name. If you want to see the value of the radio button that's checked, you need to loop through the collection:

    function getResults() {
        var radios = document.getElementsByName("question1");
    
        for (var i = 0; i < radios.length; i++) {       
            if (radios[i].checked) {
                alert(radios[i].value);
                break;
            }
        }
    }
    

    Here's a working jsFiddle.

    0 讨论(0)
  • 2020-12-07 03:27

    you can get a more simple and elegant solution:

    <input type=radio name=my_radio value=value_1>
    
    var my_form = document.querySelector('#my_form');
    var my_radio = my_form.elements.my_radio;
    
    alert(my_radio.value)  // this is the radionodelist.value you can check it on mdn
    
    0 讨论(0)
提交回复
热议问题