简体   繁体   中英

Show/Hide Form Fields on checkbox checked/unchecked

I'm using JavaScript to show/hide additional fields in my form depending on whether the relevant checkbox is clicked. The fields are hidden and they do show when the checkbox is ticked, but DO NOT hide when it is un-ticked. However, the fields do hide when I tick the checkbox again.

I have the checkbox with id='cb_post' and an onclick command to fetch showDiv() from my external javascript file. I also have the hidden field with id='hiddenDiv' .

My javascript script is simple:

function showDiv() {
    if (document.getElementById('hiddenDiv').style.display == 'block') {
        (document.getElementById('hiddenDiv').style.display = 'none');
    } else {
        document.getElementById('hiddenDiv').style.display = 'block';

    }
}

Can anyone advise on how to hide the fields when the checkbox is unticked?

You should think about using jQuery

$("#hiddenDiv").hide();
$("#hiddenDiv").show();

and something nicer

$("#hiddenDiv").fadeOut();
$("#hiddenDiv").fadeIn();

I think using jQuery toggle would fit better for your problem:

<input type="checkbox" id="cb_post">
<div id = "hiddenDiv">
<li>Toggle me</li>
</div>

$("#cb_post").on('click', function(){

    $("#hiddenDiv").toggle();

});

Maybe using the event onchange instead of onclick would be more elegant.

https://jsfiddle.net/qqL0sxxs/

Here is working code :

 var chebx = document.getElementsByClassName('toggleField'); for (var i = 0; i < chebx.length; i++) { chebx[i].addEventListener('click', toggleField, false); } function toggleField() { var field = document.getElementById(this.dataset.target); if (field) { switch (this.checked) { case true: if (field.classList.contains('hide')) { field.classList.remove('hide'); } else { field.classList.add('hide'); } break; default: break; } } } 
 .hide { display: none; } 
 <lable for='toggleField'>Toggle Field</lable> <input type="checkbox" data-target='field1' class='toggleField'> <input type='text' class='hide' id='field1' /> <hr> <lable for='toggleField'>Toggle Field</lable> <input type="checkbox" data-target='field2' class='toggleField'> <input type='text' class='hide' id='field2' /> 

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