How to display or conceal a section of the form depending on the checkbox selection?

I have a pair of checkboxes labeled First and Second

<input type="checkbox" name="checkbox1" id="checkbox1" value="checkbox1" /> First

<br />

<input type="checkbox" name="checkbox2" id="checkbox2" value="checkbox2" /> Second

Additionally, I have a form with three input fields: name, phone, and address.

<form id="f1">
<div class="form-row">

<div class="form-group col-md-6">
    <label for="first">Name</label>
    <input type="text" class="form-control" id="name" name="name" required>
</div>
<div class="form-group col-md-6">
    <label for="">Phone</label>
    <input type="text" class="form-control" id="phone" name="phone" required>
</div>
    <div class="form-group col-md-6">
    <label for="inputCity">Address</label>
    <input type="text" class="form-control" id="address" name="address" required>
</div>
</div>
</form>

If the user selects the First checkbox, only the name and phone input fields should be displayed. Similarly, selecting the Second checkbox should display the address field.

Here is what I have attempted:

https://jsfiddle.net/thorstorm1102/16hgpt0z/3/

I tried hiding the entire form using JavaScript:

var form1 = document.querySelector("#f1"),
    form2 = document.querySelector("#f2"),
    check1 = document.querySelector("#checkbox1"),
    check2 = document.querySelector("#checkbox2");

check1.onchange = function() {
form1.classList.toggle("hidden");
}

And here is the associated CSS:

.hidden {
display: none;
}

Any suggestions on how to show only specific content based on the checkbox selection?

Answer №1

In my solution, I have implemented two different options: one in plain JavaScript and the other in jQuery.

    /*---- Vanilla JS----*/
    check1.onchange = function() {
        if(this.checked){
            document.querySelector("#address").closest('.form-group').style.display = "none";
        } else {
            document.querySelector("#address").closest('.form-group').style.display = "";
        }
    }

    check2.onchange = function() {
        if(this.checked){
            document.querySelector("#name").closest('.form-group').style.display = "none";
            document.querySelector("#phone").closest('.form-group').style.display = "none";
        } else {
            document.querySelector("#name").closest('.form-group').style.display = "";
            document.querySelector("#phone").closest('.form-group').style.display = "";
        }
    }

/*----jQuery----*/
    $(document).on('change','#checkbox1',function(){
        if($(this).is(":checked")){
            $('#address').closest('.form-group').hide();
        } else {
          $('#address').closest('.form-group').show();
        }
    });

    $(document).on('change','#checkbox2',function(){
        if($(this).is(":checked")){
            $('#name').closest('.form-group').hide();
            $('#phone').closest('.form-group').hide();
        } else {
            $('#name').closest('.form-group').show();
            $('#phone').closest('.form-group').show();
        }
    });

Link to the interactive demo

Answer №2

In a previous project, I implemented a similar feature using JQuery.

function showNameAndPhone() {
  $("#address1").hide();
   $("#name1").show();
  $("#phone1").show();

}

function showAddress() {
  $("#name1").hide();
  $("#phone1").hide();
  $("#address1").show();


}
.hidden {
    display: none;
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="checkbox" name="checkbox1" id="checkbox1" value="checkbox1" onclick="showNameAndPhone()" /> First

<br />

<input type="checkbox" name="checkbox2" id="checkbox2" value="checkbox2" onclick="showAddress()" /> Second


<form id="f1">
  <div class="form-row">

    <div class="form-group col-md-6" id="name1">
      <label for="first">Name</label>
      <input type="text" class="form-control" id="name" name="name" required>
    </div>
    <div class="form-group col-md-6" id="phone1">
      <label for="">Phone</label>
      <input type="text" class="form-control" id="phone" name="phone" required>
    </div>
    <div class="form-group col-md-6" id="address1">
      <label for="inputCity">Address</label>
      <input type="text" class="form-control" id="address" name="address" required>
    </div>
  </div>
</form>

You can achieve a similar functionality by using input type = radio and giving them the same name if you want only one to be selected at a time.

I hope this solution is helpful for your current task.

Answer №3

Utilizing Radio Buttons for Enhanced Functionality

Radio buttons are designed to allow only one option to be selected at a time, making them ideal for your specific needs. Unlike checkboxes that permit multiple selections concurrently, radio buttons provide the exclusive functionality you require.

Implementing Radio Buttons in Your HTML Code

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>My first website</title>
    <link rel="stylesheet" href="css-01/css/styles.css">
  </head>
  <body>
    <input type="radio" id="male" name="gender" value="male">
      <label for="male">Male</label><br>
    <input type="radio" id="female" name="gender" value="female">
      <label for="female">Female</label><br>


    <form id="f1">
      <div class="form-row">
        <div class="form-group col-md-6">
          <label for="first">Name</label>
          <input type="text" class="form-control" id="name" name="name" required>
        </div>
        <div class="form-group col-md-6">
          <label for="">Phone</label>
          <input type="text" class="form-control" id="phone" name="phone" required>
        </div>
          <div class="form-group col-md-6">
          <label for="inputCity">Address</label>
          <input type="text" class="form-control" id="address" name="address" required>

        </div>
      </div>
    </form>
  </body>
  <script type="text/javascript" src="jquery.js"></script>
  <script type="text/javascript" src="custom.js"></script>
</html>

Enhancing Functionality with JavaScript

$('#male').click(function() {
  $("#name").show();
  $("#phone").show();
  $("#address").hide();
});

$('#female').click(function() {
  $("#name").hide().
  $("#phone").hide().
  $("#address").show();
});

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

Using jQuery to Verify Matching Objects Based on a Shared Property in Sets

I am in search of a solution using JavaScript or jQuery to ensure that two sets/arrays of objects share the same value for a particular property. In this case, two items share the same guid value across both sets, but some properties differ between them - ...

Issue with (click) event not being detected on most elements throughout Ionic 4 webpage

BACKGROUND: After working perfectly for some time, all the click events in my Ionic app suddenly stopped functioning. I have two floating action buttons that used to trigger a JS alert popup and open a modal window, but now they are unresponsive. The onl ...

Invoking a function means calling another one simultaneously

There are two buttons in my code: The button on the right triggers a function called update(): <script> function update(buttonid){ document.getElementById(buttonid).disabled = true; event.stopPropagation(); var textboxid = buttonid.sli ...

Exploring the depths of Vue.js routing through nesting

My Current Route is function route(path, view) { return { path: path, meta: meta[path], component: resolve => import(`pages/${view}View.vue`).then(resolve) } } route('/', 'Home'), route('/help', 'Help ...

Container struggling to contain overflowing grid content items

While creating a grid in nextjs and CSS, I encountered an issue. Whenever I use the following code: display: grid; The items overflow beyond the container, even though I have set a maximum width. Instead of flowing over to the next row, the items just kee ...

Error: The function (0 , _testUtils.createLocalVue) is not defined as a function

I need help troubleshooting my code. I am trying to test my Vue frontend using jest, but I keep getting the error message "TypeError: (0 , _testUtils.createLocalVue) is not a function" specifically on the line const localVue = createLocalVue(); import { ...

Using jQuery to dynamically change the label of a Struts2 checkbox

Currently, I am utilizing jquery to modify the labels of checkboxes. use strict'; $("#chId").click(function () { if (this.checked) { $('#divId').html("Checked"); } else{ $('#divId').html("Un-Checked"); ...

Retrieve all entries and merge a field with aggregated information in Mongoose (MongoDB)

I am faced with the challenge of working with two Mongo collections, Users and Activities. The Activities collection consists of fields such as createdAt (type Date), hoursWorked (type Number), and a reference to the user through the user field. On the oth ...

React Foundation accordion not functioning properly

Utilizing Foundation accordion within my React component has presented a challenge. The code functions properly when rendering static HTML, but when attempting to render it dynamically through a loop, the accordions lose their clickability. React code fo ...

How to Verify if a WebControl Contains Server-Side Blocks in ASP.NET

I am looking for a way to identify if a Web control contains server blocks in code, without necessarily parsing the entire file or scanning for specific tags. The reason for this requirement is because I have numerous old Web forms that were created witho ...

Creating JavaScript object fields with default values in an AngularJS model: A Step-by-Step Guide

As I work on developing the model layer for my AngularJS application, I came across some valuable advice on using functions to create objects. This source emphasizes the use of functions like: function User(firstName, lastName, role, organisation) { // ...

Modify the color of an Ionic button for a single button, rather than changing the color for all buttons

How can I modify this code so that only the clicked button changes its color, not all of them? Here is the current code: .html: <ion-col size="6" *ngFor="let data of dataArray" > <ion-card> <ion-card-header> ...

Scrollbar visibility issue

Recently, I came across a curious behavior regarding browser scrollbars. To see it in action, check out this link. HTML: <div class='container'> <div class='fix' /> </div> CSS: body { margin: 0; } .container ...

My attempt at deploying my personal React App project on Vercel was unsuccessful

// encountering error during deployment on Vercel npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: @testing-library/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e99b8c888a9da9d8da ...

Arranging cards in a Masonry-like column layout horizontally using Bootstrap 4 orders

Can Bootstrap 4 Cards be ordered from left to right when using the .card-columns class? By default, the order is from top to bottom: 1 3 5 2 4 6 But can they be arranged from left to right like this: 1 2 3 4 5 6 I need to use a Masonry-like grid due t ...

Learn how to utilize webpack for bundling a TypeScript library into a JavaScript script

Recently, I created a TypeScript library that I am currently using as an npm package. Here's a snippet of what it looks like: index.ts import * as peselManager from './pesel'; /** * Checks if a given PESEL number is valid. * * @param { ...

Incorrect synchronization in the SVG arrow animation

How come the arrow doesn't start moving at the same time as the line? Is there a synchronization issue? I want the arrow to begin its journey simultaneously with the line. .container{ width:100%; padding:0px; background-color: black; } .squig ...

Validating input in AngularJS with custom rules based on a resource

In my Angular application, I have a form that undergoes custom validation on all fields whenever there is a change in any field. This means that the validity of each field can change based on the values of other fields in the form, resulting in the entire ...

Having trouble replacing scss variables in react-h5-audio-player

I recently integrated react-h5-audio-player into my project and followed the instructions on the README page to customize the styles by updating the SCSS variables that control the colors. However, it appears that my custom styles are not being applied. An ...

React Apollo - Component not re-rendering when result changes

I am currently utilizing React Apollo to interact with a GraphQL backend. The function I am developing enables users to modify the admin permissions of another user. Within my setup, there are two components involved. One component houses the React Apollo ...