简体   繁体   中英

Finding value of a radio in a form after checked? Javascript DOM

I currently have this form, and I am trying to get the value of the radio buttons when it is checked but I continually keep on having an error, what may be the problem with the code below?

html

  <form name="radioset2" id="radioset2" action="survey.html">
    <fieldset>
     <span class = "question"> question1 </span>
       <div id = "radio1">
            <label for="r_q1_id">Yes</label>
            <input id="r_q1_id" type="radio" name="r_q1_name" value="yes" />
       </div>
       <div id = "radio2">
            <label for="r_q2_id">No</label>
            <input id="r_q2_id" type="radio" name="r_q1_name" value="no" />
       </div>                                       

      </fieldset>
  </form>

javascript

function validRadio() {
var radio_buttons = document.getElementsByName.elements['r_q1_name'];
for(var x=0; x<radio_buttons.length; x++) {
    if(radio_buttons[x].checked) {
    alert(radio_buttons[x].value + " button is checked");
    } else {
    alert(radio_buttons[x].value + " button is not checked");
       }
    }
    return false;
} 

If you are targetting modern browsers, you can simply use the :checked CSS selector with the querySelector function to get the value of the checked input. That would remove the need of looping over the inputs.

http://jsfiddle.net/4uy2V/

var val = document.querySelector('[name=r_q1_name]:checked').value;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM