When multiple checkboxes are selected, the corresponding form fields will be automatically filled with shared information

When the user checks multiple checkboxes, corresponding form fields should appear based on the checkboxes selected. For example, if the user checks both the flight and hotel checkboxes, the fields for full name and last name should be displayed, while other fields should be hidden.

I attempted to implement a toggle method that hides fields when checked, but I am unable to select multiple fields and display only the common fields while hiding others. Additionally, I need the checkboxes to be aligned horizontally. I have tried using CSS for alignment, but it is not working as expected.

function toggle(object){
  var input;
  var value = object.getAttribute("value"); 

  switch(value){
    case "flight":
      input = "input1";
      break;

    case "hotel":
      input = "input2";
      break;

    case "travel":
      input = "input3";
      break;
  }

  var elements = document.getElementsByClassName(input);
  for(var i = 0; i < elements.length; i++){
    if (elements[i].style.display == "block") {
      elements[i].style.display = "none";
    } else {
      elements[i].style.display = "block";
    }
  }
  document.getElementsByTagName("button")[0].style.display = "block";
}
.form-style-1{
    // CSS styles here...
}
<body>
  <div class="form-style-1">
    <form action="mailto:    ?subject=Travel Pre-approval Form "  method="post" enctype="text/plain" id="travel-form" onsubmit="test1()" >
      <fieldset>
        <!-- Checkbox inputs and form fields here... -->
      </fieldset>
    </form>
  </div>
</body>

Answer №1

There are multiple approaches to achieve the desired outcome. Here is an example:

Using CSS:

        .active{   // Adds the .active class to related group when a checkbox is selected, and removes it when unchecked
            display: block !important;
        }

        .flight, .hotel, .travel{ // Initially hides all grouped elements
             display:none;
        }

Using JavaScript:

 function toggle() {
    var sender = event.target || event.srcElement;
    var value = sender.getAttribute("value");
    var group = document.querySelector("."+value) // If there are multiple divs with the same CSS class name, use "document.querySelectorAll()" and iterate through the list to update all elements
    if(sender.checked){
       group.classList.add("active");
    }else{
      group.classList.remove("active")
    }

}

Using HTML:

<div class="form-style-1">
    <form action="mailto:    ?subject=Travel Pre-approval Form " method="post" enctype="text/plain" id="travel-form" onsubmit="test1()">
        <fieldset>
            <div>
                <input type="checkbox" onclick="toggle()" id="flight" value="flight"><label for="flight">Flight</label>
                <input type="checkbox" onclick="toggle()" id="hotel" value="hotel"><label for="hotel">Hotel</label>
                <input type="checkbox" onclick="toggle()" id="travel" value="travel"><label for="travel">Travel</label>
            </div>
            <div class="flight ">
                <label>Full Name: <input type="text" class="input1 common " id="name" placeholder="Full Name as per Passport"></label>
                <label>Date of travel:&nbsp;&nbsp; <input type="date" class="input1 common " name="num1" id="date of travel"></label>
                <label>Date of arrival: <input type="date" class="input1 common" name="num2"></label>
            </div>
            <div class="hotel ">
                <label>
                    Origin Location:
                    <select name="opt2" id="cost" onchange="calculateTotal()">
                        <option value="select">select</option>
                        <option value="Dubai, United Arab Emirates (DXB-Dubai Intl.)">Dubai, United Arab Emirates (DXB-Dubai Intl.)</option>
                    </select>
                </label>
            </div>
            <div class="travel">
                <label>
                    Destination Location: <select name="op1" id="locations" onchange="calculateTotal()">
                        <option value="none">none</option>
                        <option value="Aberdeen, Scotland, UK (ABZ)">Aberdeen, Scotland, UK (ABZ)</option>
                    </select>
                </label>
                <label>Mobile Number(Roaming) <input type="tel" id="phone"></label><br><br>
            </div>
        </fieldset>
    </form>
</div>

I hope this explanation is helpful.

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

Smoothly animate a Three.js object in response to an event without changing its current position

I need assistance with slowing down the rotation animation of a cube when a mouse hovers over it and making it continue smoothly on mouse leave. The current issue I'm facing is that when the mouse enters the cube, the rotation slows down but abruptly ...

The Bootstrap 4 card component is a versatile and stylish

Currently working on a display layout using Bootstrap 4, specifically utilizing cards. The issue I'm facing is that the text exceeds the limit of the card, causing it to overflow. Is there a solution to make the text automatically wrap to the bottom ...

I’m currently working on my webpage, utilizing HTML, CSS, and Bootstrap 4. I’ve encountered an issue where a slide keeps appearing at the bottom, but I’m

Improving HTML and Bootstrap: // Extra small devices (portrait phones, less than 576px) // No media query since this is the default in Bootstrap // Small devices (landscape phones, 576px and up) @media (min-width: 576px) { ... } // Medium devices ( ...

Unable to interact with buttons located in the title bar of the Electron application

I am currently working on developing a basic Text Editor using Electron. I am facing an issue with adding a custom title bar where the buttons are not clickable. To try and fix this issue, I have included an onclick tag to the buttons in my code. main.js ...

Unable to locate the JavaScript function

My latest 'object' creation: function Gem() { this.size = 20.0; this.body; this.isCollected = false; this.vertexPosBuffer; this.vertexColBuffer; } Next, I define a function for it: Gem.prototype.Update = function() { t ...

Having trouble with the functionality of JQuery drop feature?

As I delve into implementing drag and drop functionality with JQuery, I encounter a peculiar issue. I have set up 3 'draggable' divs and corresponding 3 'droppable' divs. The intended behavior is for each draggable element to be accepte ...

Using PHP to pass variables to an external JavaScript file

I have come across the following code snippet: PHP <?php include("db.php"); ?> <html> <head> <title>Title</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/j ...

"Use AJAX to dynamically update a div element when a button is clicked with a specific value

I have a calendar that is being displayed server side using PHP. My goal now is to allow users to scroll through the months with two buttons (<< / >>) without having to reload the entire page. I have come across many similar questions and examp ...

JavaScript Object has Not Been Defined

Currently, I am developing a small program for myself related to a video game. The main issue I am facing is that certain objects are being flagged as not defined when the errors appear on the page. $(document).ready(function(){ //A list of chara ...

Exploring the possibilities of integrating Keycloak with the powerful nuxt-auth

I am incorporating this particular authentication module in conjunction with Keycloak. In my nuxt.config.js configuration: keycloak: { _scheme: 'oauth2', client_id: 'client-bo', userinfo_endpoint: 'SERVER/protocol/open ...

Creating responsive arrow heads using D3: A step-by-step guide

Currently, I am working on creating a thermometer-style bar chart using D3.js version 3. While I have successfully created a basic responsive rectangle with two filled colors, I am facing difficulties in figuring out how to add arrow heads to the design. B ...

Navigating the Angular Element: A Guide to Clicking Buttons within Modal-Dialogs Using Protractor

I am currently creating an automation test for an angular application using the protractor framework. Test scenario: Click on the "Create PDF Report" button A modal-dialog window will appear Click on the "Run Report Now" button within the modal-d ...

Picture disappearing following the refresh of an AJAX iframe

Currently, I am developing a profile system where the user's profile is displayed in an iframe that reloads when the form submit button is clicked. The content updates successfully upon reloading, but there is an issue with images not displaying after ...

Implementing a JavaScript confirmation based on an if-else statement

I need to display a confirmation dialog under certain conditions and then proceed based on the user's response of yes or no. I attempted the following approach. Here is the code in aspx: <script type="text/javascript> function ShowConfirmati ...

I am attempting to set up React, but I keep encountering an issue that says 'Error: EPERM: operation not allowed'

My attempts to set up React have been unsuccessful so far. Initially, I tried installing it using the command npx create-react-app ./, which did not work. Then, I attempted to run npm init react-app my-app, but unfortunately, that also failed. The error me ...

Programming in Python often involves utilizing a combination of powerful libraries such as BeautifulSoup,

I am currently developing a program that is designed to extract emails and collect specific links from them, particularly those from Newegg. I have successfully used iMAP to log in and access the HTML content of the emails. However, I am encountering an is ...

Enhancing transparency with a touch of background color

After successfully exporting my chart created in canvas as an image file, I noticed that the image turned out to be transparent without any background. Is there a way through code to add a background color to this existing image obtained from canvas? For ...

How can one decrease the size of a React project?

After running npx create-react-app my-app, the download was quick but then it took over an hour for the installation process to complete. Upon checking the size of the newly installed project, I found that the node_modules folder alone was a whopping 4.24 ...

Employing ExpressJS on the server side and JQuery on the client side for handling static links

Recently delved into the world of jQuery and node.js, and everything was smooth sailing until I hit a roadblock. Despite my best efforts to search online, I couldn't find a solution to my problem. It seems like a simple issue, but I just can't fi ...

Execute the Selenium function repeatedly using values from an array in a loop

I am facing a challenge with running a selenium script in a loop to populate a database. I have an array of objects consisting of 57 items that need to be processed through the loop asynchronously. My goal is to iterate through each store, check its status ...