Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught TypeError: Cannot set property 'onclick' of null [duplicate]

I'm having problems making my window alert pop up with a simple checkbox and can't for the life of me figure out why. Here's the basic Javascript and HTML:

var blue_box=document.getElementById("color-blue");  function colorFunction() {      window.alert("This color is blue!");  }    blue_box.onclick=colorFunction;
<form action="" method="POST" id="form">      <fieldset>          <legend> Form!</legend>          <ul>              <li><label><input type="checkbox"                       name="color"                       value="blue"                       id="color-blue" />                      blue</label>                  </li>  	        <li><label><input type="checkbox"                       name="color"                        value="red"                       id="color-red" />                      red</label>                  </li>  		<li><label><input type="checkbox"                       name="color"                       value="yellow"                       id="color-yellow" />                      yellow </label>                  </li>              </ul>          </fieldset>      </form>

Which throws: Uncaught TypeError: Cannot set property 'onclick' of null under

blue_box.onclick=colorFunction; 

Are there any visible reasons for this error in my code?

like image 959
user1279662 Avatar asked Mar 19 '12 22:03

user1279662


People also ask

Why is my button null in Javascript?

This is usually caused by putting the script in the head and trying to access elements in the body . Approaches to deal with this include: Moving the <script> so it appears after the element you are trying to access. This could be directly after it or just before the </body> tag.

Can not set properties of undefined?

The "Cannot set properties of undefined" error occurs when setting a property on an undefined value. To solve the error, conditionally check if the value is of the expected type (object or array) or has to be initialized before setting the property on it.


1 Answers

Wrap code in

window.onload = function(){      // your code  }; 
like image 98
maximkou Avatar answered Sep 25 '22 06:09

maximkou