Reputation: 3
I am making a form that will have checkboxes and entry text. When a checkbox is check, related text should appear adjacent to it. This is my current code, but it does not work: HTML:
<input type="checkbox" class="box1" onchange="showHide()"> Option 1
<div class="hid box1">
<select name="option1">
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
Comments: <input type="text" name="option1Comment">
</div>
CSS:
.hid {
display: none;
}
JavaScript:
function showHide() {
var checkBox = document.getElementByClassName(this);
var text = document.getElementByClassName(this "hid");
if (checkBox.checked == true){
text.style.display = "block";
} else {
text.style.display = "none";
}
}
Upvotes: 0
Views: 1149
Reputation: 732
There are a couple of things you should fix in your code.
First, you could change the function call on the <input>
from
onchange="showHide()"
to onchange="showHide(this)"
Then, you could fix the syntax of getElementByClassName
on your function or change it to querySelector
to get just the one Node
you want.
After that you could do something like this to hide or show your <div>
:
function showHide(element) {
let checkboxClass = element.classList[0];
let div = document.querySelector("div.hid." + checkboxClass);
div.style.display = (element.checked) ? "block" : "none";
}
Upvotes: 1