Reputation: 732
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
In this case, how I fix this error?
Thanks.
Upvotes: 2
Views: 64594
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
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
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:
Upvotes: 1