Skip to content Skip to sidebar Skip to footer

Getelementbyid Not Playing Nice With Radio Buttons

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: Copy

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

alert(getRadioVal("group1"));

Solution 2:

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

window.onload = function() {
    alert(getRadioValue());
}

Solution 3:

As others have pointed out, you will have to put your code in load/ready events.

Also, your code will alwasy return 'h264', you will have to check for the checked attribute.

You will have to iterate through radio buttons to find which one is selected.

functiongetRadioValue()
{
    var radio1 = document.getElementById('radio1');
    var radio2 = document.getElementById('radio2');

    //You sould not hard code the value of HTML radio button in your code.//If you change value in HTML code, you will have to modify your JS code as well.return radio1.checked ? radio1.value : radio2.value;
}

Also, it will be better idea not to write this JavaScript code by hand but use library like jQuery. Your code will become as simple as,

$("input[name='group1']:checked").val();

Solution 4:

This works on my machine; have you tried a minimal example like the following?

<html><form><inputid="radio1"type="radio"name="group1"value="h264"checked="checked" /><inputid="radio2"type="radio"name="group1"value="flv" /></form><scripttype="text/javascript">alert(document.getElementById("radio1"));
    </script></html>

My guess is that you're not waiting until after the radio1 element is created to reference it. Use the DOMContentLoaded or load events.

Solution 5:

Josh's note above was really helpful, I made a slight modification to stop the function returning all the elements of the objects - this seemed to work OK for me

functiongetRadioVal(radioName) {
      var rads = document.getElementsByName(radioName);
      for (var rad=0;rad<=rads.length-1;rad++) {
        if(rads[rad].checked) {
          return rads[rad].value; 
        }
      }
      return null;
    }

    alert(getRadioVal("group1")); 

Post a Comment for "Getelementbyid Not Playing Nice With Radio Buttons"