简体   繁体   中英

How to change text display when checkbox checked

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";
    }
}

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";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM