Reputation: 45
I get the error "Unable to get the value of the property 'checked'. object is null or undefined." when clicking a checkbox.
The form's name is 'test', and I want to display more input fields based on the first check box being checked, if they pass by it then I do not want the other fields displayed.
Here's the script:
function showhidefield()
{
if (document.test.submode.checked) {
document.getElementById("hideablearea").style.display = "block";
} else {
document.getElementById("hideablearea").style.display = "none";
}
}
Here's my input line:
<input type="checkbox" name="submode" onclick="showhidefield()">
Is there a way I can make my JS more solid so it works on this other web page and on any browser?
Upvotes: 1
Views: 1679
Reputation: 173642
There will not always be a <form>
on the page with the name "test"
.
You can make it work without an id by using this
to reference the current element:
<input type="checkbox" name="submode" onclick="showhidefield(this, 'hideablearea')">
JavaScript:
function showhidefield(element, id)
{
var node = document.getElementById(id);
if (node) {
node.style.display = element.checked ? 'block' : 'none';
}
}
The first argument to the function is the checkbox itself and the second argument is the id of the element you wish to show or hide.
Upvotes: 0
Reputation: 324750
Put an ID on the checkbox, and use getElementById
. This is more reliable than other methods, since IDs are required to be unique.
Upvotes: 1