3

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

5
  • 1
    Small tip: since you seem to be XHTMLing (inferred via the closing slash), you should put checked="checked", not just checked.
    – Domenic
    Jul 4, 2009 at 17:10
  • Good Point, thanks. Sloppy JavaScript as well as xHTML. :)
    – Abs
    Jul 4, 2009 at 17:13
  • Something else must be wrong. Your code should work Jul 4, 2009 at 17:13
  • Aaaah - I just realized, I remove elements then reference it! Sorry everyone!! :)
    – Abs
    Jul 4, 2009 at 17:20
  • As I wrote in my answer, do not repeat radio button values in your JS code. Find the value from the selected radio button. Jul 4, 2009 at 17:20

6 Answers 6

8

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"));
5

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

window.onload = function() {
    alert(getRadioValue());
}
3
  • Yes. this managed to work. But I wait for at least 5 seconds after page load yet it gives me a null??
    – Abs
    Jul 4, 2009 at 17:17
  • Chosen as you where the first closest correct answer. Apologies once again everyone.
    – Abs
    Jul 4, 2009 at 17:22
  • That's because your element was still not loaded. Do you have a large document or are you retrieving the content from the server via xmlhttprequest?
    – Fernando
    Jul 4, 2009 at 17:23
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.

function getRadioValue()
{
    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();
2
  • I use JQuery in my other projects, but this is a very small project and I don't think the overhead of the JQuery library is worth it. :)
    – Abs
    Jul 4, 2009 at 17:21
  • 1
    Overhead of the jQuery library? Other than adding one line in your head section, I don't think there is any overhead. I am sure you would have wasted WAY MORE time to debug this problem compared to including the library in the first place. For me, even if I was creating a throw away sample code, I would include jQuery. Jul 4, 2009 at 17:26
1

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

<html>
    <form>
        <input id="radio1" type="radio" name="group1" value="h264" checked="checked" />
        <input id="radio2" type="radio" name="group1" value="flv" />
    </form>
    <script type="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.

2
  • 1
    How long do you have to wait. I waited 5 seconds after page load and now a full minute. Surely it should be quicker??
    – Abs
    Jul 4, 2009 at 17:18
  • It depends on the document. That's why you need to use the events I referenced; they will execute your function as soon as it is possible, but no sooner. (The difference between them being that DOMContentLoaded will not wait for any images e.g. to fill themselves in, whereas the load event will. So DOMContentLoaded will be sooner.)
    – Domenic
    Jul 4, 2009 at 17:25
1

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

    function getRadioVal(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")); 
0

I always compare my code with the recordings created by the iMacros Firefox addon. Its very useful as a reference!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.