JavaScript read radio button value in IE and FireFox

前端 未结 5 839
眼角桃花
眼角桃花 2021-01-21 05:02

I have a simple web form that uses JavaScript for building a POST statement. In Chrome, I can use a simple line of code...

var form = document.forms[\'myForm\'];         


        
相关标签:
5条回答
  • 2021-01-21 05:04

    Try this

    function getValueFromRadioButton(name) {
       //Get all elements with the name
       var buttons = document.getElementsByName(name);
       for(var i = 0; i < buttons.length; i++) {
          //Check if button is checked
          var button = buttons[i];
          if(button.checked) {
             //Return value
             return button.value;
          }
       }
       //No radio button is selected. 
       return null;
    }
    

    IDs are unique so you should not use the same ID for multiple items. You can remove the all the radio button IDs if you use this function.

    0 讨论(0)
  • 2021-01-21 05:09

    You are using the same ID for multiple Elements, ID is unique for element on the page.

    use different IDs.

    edit: names can be the same. because then the radio buttons are as a group.

    0 讨论(0)
  • 2021-01-21 05:10

    As stated, the IDs should be different to be valid, but you could accomplish this by eliminating the IDs all together and using just the input name:

    var form = document.forms['myForm'];
    var radios = form.elements["env"];
    var env = null;
    for(var i=0;i<radios.length;i++) {
        if(radios[i].checked == true) {
            env = radios[i].value;
        }
    }
    
    <form name="myForm">
    <input type="radio" name="env" value="inside">Inside
    <input type="radio" name="env" ivalue="outside" checked="checked">Outside
    <input type="radio" name="env" value="both">Both
    <input type="radio" name="env" value="neither">Neither
    </form>
    
    0 讨论(0)
  • 2021-01-21 05:12

    Short & clear on ES-2015, for use with Babel:

    function getValueFromRadioButton( name ){
      return [...document.getElementsByName(name)]
             .reduce( (rez, btn) => (btn.checked ? btn.value : rez), null)
    }
    
    console.log( getValueFromRadioButton('payment') );
    <div>  
      <input type="radio" name="payment" value="offline">
      <input type="radio" name="payment" value="online">
      <input type="radio" name="payment" value="part" checked>
      <input type="radio" name="payment" value="free">
    </div>

    0 讨论(0)
  • 2021-01-21 05:22

    You can try this:

    var form = document.querySelector('form#myForm');
    var env_value = form.querySelector('[name="env"]:checked').value;
    
    0 讨论(0)
提交回复
热议问题