Peter
Peter

Reputation: 732

Uncaught TypeError: Cannot set property 'checked' of null

I am using a Javascript at javascript Hide/show div on checkbox: checked/unchecked.

var elem = document.getElementById('powermail_fieldwrap_331'),
    checkBox = document.getElementById('powermail_field_doruovaciaadresa2_1');
checkBox.checked = false;
checkBox.onchange = function doruc() {
    elem.style.display = this.checked ? 'block' : 'none';
};
checkBox.onchange();

I changed "checkBox.checked = false;" to "checkBox.checked = true;" It works anyway but produces an error: Uncaught TypeError: Cannot set property 'checked' of null

Demo

In this case, how I fix this error?

Thanks.

Upvotes: 2

Views: 64594

Answers (4)

Rinku Choudhary
Rinku Choudhary

Reputation: 2161

Your document.getElementById("checkboxid") contains null value. For that store it in a variable and then you can check like

  var checkbox = document.getElementById("chkteam");
        if (checkbox == true) {

         // your condition 
        }

Then It will Work.

Upvotes: 1

thaimechatronics
thaimechatronics

Reputation: 1

You need to change all of tag without checked by

Upvotes: 0

Sebastian Nette
Sebastian Nette

Reputation: 7812

The fiddle works fine. The only issue can be that the script is executed before the checkbox was part of the DOM.

Either wrap your code within an onload event.

window.onload = function() {
    var elem = document.getElementById('powermail_fieldwrap_331'),
    checkBox = document.getElementById('powermail_field_doruovaciaadresa2_1');
    checkBox.checked = false;
    checkBox.onchange = function doruc() {
        elem.style.display = this.checked ? 'block' : 'none';
    };
    checkBox.onchange();
};

Or make sure that the script tag is written after the checkbox is part of your DOM:

<label>
    <input type="checkbox" id="powermail_field_doruovaciaadresa2_1" checked="checked" />
    Show/hide
</label>
<div id="powermail_fieldwrap_331">Lorem ipsum</div>

<script>
var elem = document.getElementById('powermail_fieldwrap_331'),
    checkBox = document.getElementById('powermail_field_doruovaciaadresa2_1');
    checkBox.checked = true;
    checkBox.onchange = function() {
        elem.style.display = this.checked ? 'block' : 'none';
    };
    checkBox.onchange();
</script>

Upvotes: 4

Barr J
Barr J

Reputation: 10919

Your code executes, before the document is fully ready, which is causing you to receive the ID as null, since it is not rendered yet.

It is a common problem, this is why in jquery you always use $(document).ready();

To make sure, that the document is fully loaded first and no elements will be executed before the document is fully loaded, preventing errors like this.

There is a very helpful post regarding this in java script:

Pure java script jquery ready

Upvotes: 1

Related Questions