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?
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.
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.
Wrap code in
window.onload = function(){ // your code };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With