0

I have the error: index.html:12 Uncaught TypeError: Cannot read property 'addEventListener' of null Not sure what went wrong? The code is suppose to store the result of the radio button selected into an array. But the function does not even run because it is null.

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Video Test</title>
    <script>
      var arr = [];
      document.getElementById("continue").addEventListener("click", function() {
          var cbChecked = document.querySelectorAll('[name="white"]:checked')
          if (cbChecked != null) {
            arr.push(cbChecked.value)
          }
          console.log(arr)
      }) 
    </script>
  </head>
  <body>
    <div id="container">
      <div id="overlay">
        <form action="">
          <input type="radio" name="white" value="1" id="radio1"/>
          <input type="radio" name="white" value="2" id="radio2"/>
          <input type="radio" name="white" value="3" id="radio3"/>
          <input type="radio" name="white" value="4" id="radio4"/>
          <input type="button" id="continue" value="Continue"/>
        </form>
      </div>
      <div id="base">
        <video controls>
          <source src="videos/event_0_Junli_Standing_20150322_181647_00_0.6.mp4" type="video/mp4">
          Your browser does not support the video tag.
        </video>
      </div>
    </div>
  </body>
</html>
Alex Ker
  • 55
  • 1
  • 8

2 Answers2

0

You are running your <script> before the DOM elements are there. Move the <script> to the bottom of the <body> tag.

zero298
  • 20,481
  • 7
  • 52
  • 83
0

querySelectorAll returns an array of objects, not a single object.

var arr = [];
      document.getElementById("continue").addEventListener("click", function() {
          var radios = document.querySelectorAll('input:checked')          
          if (radios.length > 0) {
            arr.push(radios[0].value)
          }
          console.log(arr)
      })
<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Video Test</title>
    <script>
   
    </script>
  </head>
  <body>
    <div id="container">
      <div id="overlay">
        <form action="">
          <input type="radio" name="white" value="1" id="radio1"/>
          <input type="radio" name="white" value="2" id="radio2"/>
          <input type="radio" name="white" value="3" id="radio3"/>
          <input type="radio" name="white" value="4" id="radio4"/>
          <input type="button" id="continue" value="Continue"/>
        </form>
      </div>
      <div id="base">
        <video controls>
          <source src="videos/event_0_Junli_Standing_20150322_181647_00_0.6.mp4" type="video/mp4">
          Your browser does not support the video tag.
        </video>
      </div>
    </div>
  </body>
</html>
Nate Anderson
  • 670
  • 5
  • 17