Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getElementById not playing nice with Radio Buttons

Tags:

javascript

I am guessing getElementById doesn't work with radio buttons when you want to get the value of it or to find out if it is checked? I say this because I did this:

<input id="radio1" type="radio" name="group1" value="h264" checked="checked" />
<input id="radio2" type="radio" name="group1" value="flv" />

To get the value of the selected one I did this:

function getRadioValue() {

    if(document.getElementById('radio1').value=='h264'){
        return 'h264';
    }
    else{
        return 'flv';
    }

}

However, firebug keeps telling me:

document.getElementById("radio1") is null
[Break on this error] if(document.getElementById('radio1').checked==true){

What am I doing wrong?

Thanks all

like image 733
Abs Avatar asked Dec 01 '22 07:12

Abs


2 Answers

Here is a reliable function to get the radio button selection. Since radio buttons are grouped by the name attribute, it makes sense to use getElementsByName...

function getRadioVal(radioName) {
  var rads = document.getElementsByName(radioName);

  for(var rad in rads) {
    if(rads[rad].checked)
      return rads[rad].value;
  }

  return null;
}

In your case, you'd use it like this...

alert(getRadioVal("group1"));
like image 97
Josh Stodola Avatar answered Dec 04 '22 07:12

Josh Stodola


You should call document.getElementById after the document is loaded. Try executing your code like this:

window.onload = function() {
    alert(getRadioValue());
}
like image 40
Fernando Avatar answered Dec 04 '22 08:12

Fernando