javascripthtmlcssgoogle-apps-scriptweb-applications

HTML form visible or hidden based on checkbox condition


I want to hide/visible a form based on checkbox in google webapp. If the checkbox is in checked condition then the form will be in visible else it should in hidden. I want to try with below mentioned code block. But not happen.

if (document.getElementById("df1").checked) {
   document.getElementById("co").style.visibility = "hidden";
} else {
   document.getElementById("co").style.visibility = "visible";
}
<form id="co" style="visibility : hidden">
<br>
<label type="text">Name </label><input type="text">
<br>
<label type="text">Roll No. </label><input type="number" value="0" min="0">
<br><br>
<input type="submit" value="submit">

<input type="checkbox" id="df1">


Solution

  • The issue is because the state of your checkbox is only evaluated when the page first loads. You need to instead attach an event handler to the checkbox so that the DOM can be updated as the checkbox is interacted with.

    Also note that the logic to toggle visibility can be made more simple by using a class.

    Here's working example:

    const cb = document.querySelector('#df1');
    const form = document.querySelector('#co');
    
    cb.addEventListener('change', e => {
      form.classList.toggle('hidden', !e.target.checked);
    });
    .hidden {
      visibility: hidden;
    }
    <form id="co" class="hidden">
      <br>
      <label type="text">Name </label><input type="text">
      <br>
      <label type="text">Roll No. </label><input type="number" value="0" min="0">
      <br><br>
      <input type="submit" value="submit">
    </form>
    
    <input type="checkbox" id="df1">