Checking Value of Radio Button Group via JavaScript?

前端 未结 8 638
清歌不尽
清歌不尽 2020-12-12 20:36

This may seem silly and downright stupid but I can\'t seem to figure out how to check the value of a radio button group in my HTML form via JavaScript. I have the following

相关标签:
8条回答
  • 2020-12-12 21:01

    Without loop:

    document.getElementsByName('gender').reduce(function(value, checkable) {
        if(checkable.checked == true) 
            value = checkable.value; 
        return value;
    }, '');
    

    reduce is just a function that will feed sequentially array elements to second argument of callback, and previously returned function to value, while for the first run, it will use value of second argument.

    The only minus of this approach is that reduce will traverse every element returned by getElementsByName even after it have found selected radio button.

    0 讨论(0)
  • 2020-12-12 21:04

    In pure Javascript:

    var genders = document.getElementsByName("gender");
    var selectedGender;
    
    for(var i = 0; i < genders.length; i++) {
       if(genders[i].checked)
           selectedGender = genders[i].value;
     }
    

    update

    In pure Javascript without loop, using newer (and potentially not-yet-supported) RadioNodeList :

    var form_elements = document.getElementById('my_form').elements;
    var selectedGender = form_elements['gender'].value;
    

    The only catch is that RadioNodeList is only returned by the HTMLFormElement.elements or HTMLFieldSetElement.elements property, so you have to have some identifier for the form or fieldset that the radio inputs are wrapped in to grab it first.

    0 讨论(0)
提交回复
热议问题