GetElementById doesn't play well with radio buttons

I assume that getElementById does not work with radio buttons if you want to get its value or 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, I did the following:

function getRadioValue() {

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

}

However, firebug continues to tell me:

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

What am I doing wrong?

Thank you all

+3
source share
6 answers

After loading the document you should call document.getElementById. Try to execute your code as follows:

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

. name, getElementsByName...

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

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

  return null;
}

:

alert(getRadioVal("group1"));
+7

, /.

, alwasy 'h264', .

, , .

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;
}

, JavaScript , jQuery. ,

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

; ?

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

I assume that you do not wait until the radio1 element is created to refer to it. Use events DOMContentLoadedor load.

+1
source

Josh's note above was really useful, I made a small modification to stop the function returning all elements of the objects - this seemed to work fine 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")); 
+1
source

I always compare my code with the entries created by the iMacros Firefox addon. This is very useful as a reference!

0
source

Source: https://habr.com/ru/post/1711857/


All Articles