Show or hide HTML form based on checkbox status

I have a task to show or hide a form based on the status of a checkbox in a Google web application. If the checkbox is checked, then the form should be visible; otherwise, it should be hidden. I attempted to achieve this using the code provided below, but it didn't work as expected:

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

Answer №1

Your checkbox is only evaluated when the page loads, causing an issue with updating its state. To fix this, you should attach an event handler to the checkbox so that the DOM can be updated as the checkbox is interacted with.

Additionally, consider simplifying the logic by using a class to toggle visibility.

Check out this 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">

Answer №2

Using simple HTML and CSS:

input#df1:checked ~ form#co {
    visibility: visible;
}
form#co {
    visibility: hidden;
}
<input type="checkbox" id="df1" />
<label for="df1">Show Form</label>

<form id="co">
    <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>

If JavaScript is necessary:

const cb = document.getElementById("df1")
const form = document.getElementById("co")

cb.addEventListener("change", (e) => {
    if (e.target.checked) form.style.visibility = "visible"
    else form.style.visibility = "hidden"
})
<input type="checkbox" id="df1" />
<label for="df1">Show Form</label>

<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" />
</form>

Answer №3

  1. Hide the form.
  2. Reposition the checkbox outside the form.
  3. Create a function and utilize addEventListener on the checkbox.

window.addEventListener('load', () => { // when the elements are available
  document.getElementById('df1').addEventListener('click', (e) => {
    const show = e.target.checked;
    document.getElementById("co").style.visibility = show ? 'visible' : 'hidden';
  });
});
<form id="co" style="visibility : hidden">
  <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">

Utilizing hidden attribute to conserve space:

window.addEventListener('load', () => { // when the elements are available
  document.getElementById('df1').addEventListener('click', (e) => {
    document.getElementById("co").hidden = !e.target.checked;
  });
});
<form id="co" hidden>
  <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">

Answer №4

Is this the right solution?

function toggleFormVisibility() {
  const form = document.getElementById("co");
  form.style.display = document.getElementById("df1").checked ? "block" : "none";
}
<form id="co" style="display: none">
  <br>
  <label for="name">Name</label>
  <input type="text" id="name">
  <br>
  <label for="rollNo">Roll No.</label>
  <input type="number" id="rollNo" value="0" min="0">
  <br><br>
  <input type="submit" value="submit">

</form>
 <input type="checkbox" id="df1" onclick="toggleFormVisibility()">

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a custom internal link with parameters using Twig

I am trying to create a link using this code: {{ path('article_show', { 'slug': article.slug }) }} but for an internal link format, such as: <a href="#ID_name">...</a> within an HTML context, while also passing one or mo ...

Tips for ensuring an HTML element remains within defined boundaries

Currently working on a visualization tool for search algorithms using React, I've encountered a minor issue when moving the start or end nodes. Upon clicking and dragging the mouse across the grid, the nodes adjust accordingly until reaching the grid& ...

What causes the position: sticky; property to fail in React implementations?

Currently, I am facing a challenge in making two sidebars sticky so that they will follow as the user scrolls until they reach the bottom of the page. In my current editing project, this implementation seems to be more complex compared to other programs w ...

problem of underlining links in bootstrap

Recently, I integrated a template into my ASP.Net MVC project and added all the required files to it. I made sure to include all the necessary calls to format files (CSS) in the layout file while removing any references to default styling files. However, ...

Search for specific item within an array of objects

Working on an Angular project, I am attempting to remove an object from an array. To achieve this, I need to filter the array and then update the storage (specifically, capacitor/storage) with the modified array. Here is my function: deleteArticle(id: str ...

Return Date objects in Node.js, not strings

When working with nodejs and express, I've encountered an issue where Date objects are automatically converted to strings. This has caused some confusion for me as I would prefer to send Date objects directly as a result. app.get('/', (req, ...

Merging a VUE project and a .NET framework project to unleash their full potential

Currently, I am working on a project that involves using VUE for the client side and .net framework for the server side. However, these two components are hosted as separate projects, requiring me to open different ports during development. I am aware tha ...

Prevent further triggering of the .click function when the user clicks repeatedly

Is there a way to prevent the .click function from executing if the user clicks too many times? This is my current code: $('button').click(function() { $('#bg').fadeToggle('200'); }); Check out the jsfiddle DEMO ...

Tips for maintaining the dropdown selection when new rows or columns are added to a table

I have a task requirement where I must generate a dynamic table using jQuery. I've successfully implemented adding dynamic columns or rows to the table. Feel free to check out the fiddle code here. HTML: <div id='input_div' name='i ...

The AJAX functionality seems to be failing to load the additional JavaScript and CSS files

Using a brief AJAX code, I fetch Facebook content from a PHP file where class="gallery-img-link" is defined as <a> and class="img-responsive img-thumbnail" is declared as <img>. The issue arises when attempting to load these classes via an AJA ...

Utilize lodash to locate the key of an object with deeply duplicated values

Looking at the object provided below: var data = { 2: [[1,2],[3,4,5],[6,7]], 3: [[1,2],[3,4],[6,7]], 4: [[1,2],[3,4,5],[6,7]], 5: [[10,2],[3,4,5],[60,7]] } I am interested in retrieving the key 2 from the object as its ...

Optimizing Three.js for better performance

Recently, I delved into working with three.js and webgl for a personal project. My goal was to develop a wardrobe model based on user input. You can check out the project at this link: Initially, the rendering speed was fast and smooth without Materials a ...

The call stack reached its maximum size while attempting to send a post request in an Express application

'Error Occurred: RangeError: Maximum Call Stack Size Exceeded' When Making a Post Request in Node.js with Express and body-parser As a beginner in the world of node.js, my journey took a challenging turn while following along with video #30 from ...

Transformation of JSON data from Array to Object

I have a JSON data structure that looks like this: { tag: 'new-tag', stream_subjects: [1, 2, 3] } My goal is to transform it into the following format: { tag: 'new-tag', stream_subjects: [ {subject_id: 1}, {subject_id ...

Struggling with the functionality of having numerous jQuery UI controls on a single page. Implementing the accordion control in multiple sections

For my current project, I am utilizing the jQuery UI accordion control twice on a single page. The first one functions perfectly fine, but when I attempt to add a second accordion, the original one stops working while the new one works correctly. Does any ...

What is the best way to create a box in the shape of an octagon

Trying to achieve the unique box design shown below using CSS. I researched various resources, such as https://css-tricks.com/examples/ShapesOfCSS/, but encountered an issue with the purple border cutting edges. Attempted using an octagon shape without su ...

Prevent page from refreshing on mobile devices using JavaScript

I have been attempting to prevent page refresh on a mobile device through touch scroll events. After researching online, I came across the following method: /* w = flag indicating if pageYOffset was 0 before attempting to scroll below it h = last pageYOffs ...

The hyperlink functionality is disabled because Javascript is set to return false

JS Fiddle Example When using the 'FOO' and 'BOO' items in the navigation bar to open dropdown boxes, I have implemented a code that closes them when a click event occurs outside. This code has been working fine as shown below: $(docum ...

Can you explain the function of the * CSS operator? Are there any additional CSS operators that serve similar purposes?

While researching how to create a nested table using list elements in CSS, I came across this interesting page: . Upon examining the stylesheet, I noticed unfamiliar symbols being used that appear to be CSS operators, such as the > and * symbols. For ...

Inconsistencies in JavaScript comparison across various web browsers

Here is a snippet from my JavaScript code var dataList = eval(strArray[0]); for (i = 0; i < dataList.length; i++) { console.log(((dataList[i].isFollowed == 0) ? "Follow" : "Unfollow")); } However, this code exhibits varying behavio ...