Upon selecting multiple checkboxes, corresponding form fields will be displayed based on shared attributes

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

I attempted to implement a toggle method to hide/show fields when a checkbox is checked, but I am facing challenges in selecting multiple fields together and hiding others. Additionally, I need my checkboxes to be aligned horizontally using CSS, but it's not functioning as expected.

Answer №1

Take a look at this condensed and generalized CSS-only solution for toggling form fields conditionally with checkboxes:

.form__field {
display: block;
}
[class*="--checkbox"] {
display: inline-block;
}
[data-conditional] {
display: none;
}
#flight:checked ~ [data-conditional*="flight"] {
display: block;
}
#hotel:checked ~ [data-conditional*="hotel"] {
display: block;
}
#travel:checked ~ [data-conditional*="travel"] {
display: block;
}
<form action="mailto:?subject=Travel Pre-approval Form " method="POST" enctype="text/plain" id="travel-form" onsubmit="test1()">

<input class="form__input form__input--checkbox" type="checkbox" id="flight" />
<label class="form__field form__field--checkbox" for="flight">
<span class="form__label">Flight</span>
</label>

<input class="form__input form__input--checkbox" type="checkbox" id="hotel" />
<label class="form__field form__field--checkbox" for="hotel">
<span class="form__label">Hotel</span>
</label>

<input class="form__input form__input--checkbox" type="checkbox" id="travel" />
<label class="form__field form__field--checkbox" for="travel">
<span class="form__label">Travel</span>
</label>

<label class="form__field form__field--text" data-conditional="flight hotel">
<span class="form__label">Full Name:</span>
<input class="form__input" type="text"  placeholder="Full Name as per Passport" />
</label>

<label class="form__field form__field--date" data-conditional="flight hotel">
<span class="form__label">Date of travel:</span>
<input class="form__input" type="date" />
</label>

<label class="form__field form__field--date" data-conditional="flight hotel">
<span class="form__label">Date of arrival:</span>
<input class="form__input" type="date" />
</label>

<label class="form__field form__field--text" data-conditional="flight">
<span class="form__label">For Flight only:</span>
<input class="form__input form__input--text" type="text" />
</label>

<label class="form__field form__field--text" data-conditional="hotel">
<span class="form__label">For Hotel only:</span>
<input class="form__input form__input--text" type="text" />
</label>

<label class="form__field form__field--text" data-conditional="travel">
<span class="form__label">For Travel only:</span>
<input class="form__input form__input--text" type="text" />
</label>

<div class="form__field form__field--submit">
<button type="submit">Submit</button>
</div>
</form>

My checkboxes should be aligned horizontally.

The code snippet provided above satisfies the horizontal alignment of the checkboxes.

By using checkboxes to toggle form fields based on the data-conditional attribute, we can control which fields are displayed. The key technique here is the general next sibling selector in CSS combined with specific HTML markup.

Additional fields have been included at the end of the form to demonstrate how the conditional filtering works for individual checkboxes.

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

What could be causing the Gruntfile to throw an error?

Getting an unexpected error while trying to run grunt $ grunt Loading "Gruntfile.js" tasks...ERROR >> SyntaxError: Unexpected token : Warning: Task "default" not found. Use --force to continue. Execution terminated due to warnings. Here is my ...

Move to the top of the page when the next action is activated

I am working with an Angular 8 application. Within the application, I have implemented navigation buttons for next and previous actions. My goal is to ensure that when a user clicks on the "next" button, the subsequent page starts at the top of the page ...

The callback function within the Service does not execute just once when utilizing $timeout

Looking to implement a service that functions similarly to this example. Here is the code I have so far: app.service('Poller', function ($q, $http, $timeout) { var notification = {}; notification.poll = function (callback, error) { return $ ...

Leveraging React hooks to combine an array and an object within an array

Struggling to incorporate an array and an object into another array. This is the setup in my constructor: const [dashboard, setDashboard] = useState({ loading: true, data: [], address: '' }) This is how I envision the final data structure: { ...

Incorporate 'Additional features' into the Navbar when adjusting window size

When the window is resized, I want to display a collapsed 'More options' button that will collapse all hidden <li> elements. Here is an example: <li id="menu_more_container" class="dropdown" style="display: none; ...

Instructions for manipulating and displaying a source array from a child component using Vue

I have a parent component with an array that I display in the template. My goal is to click on a link that uses vue-router with a dynamic id attribute, and then open a new component displaying only the element of the array that corresponds to that id. Howe ...

JavaScript method to clear a variable

Can JavaScript prototype be used to add a method to a variable that is undefined? For instance, we can use the following code: var foo = "bar"; String.prototype.doTheFoo = function(){ console.log("foo is better than you"); }; foo.doTheFoo(); This c ...

Tips for deactivating the highlight on a previously selected menu item when clicking on the next menu option in Angular.js

In my pages, I have a menu where the landing page menu is initially highlighted. However, when I move to the next menu, the previous landing page highlight remains instead of being removed while swapping the menu. I am using Angular.js and angular ui-route ...

Using jQuery to toggle the visibility of div elements while displaying an indicator

A query arises regarding the utilization of JQuery to facilitate toggling the visibility of text divs. The question pertains to how one can incorporate an indicator - such as an up and down arrow graphic - to denote whether the divs are open or closed. Sug ...

From dividing into three sections to splitting into two sections

Struggling to create a list of images and descriptions in sets of threes at larger widths, transitioning to twos at smaller widths? The breakdown is causing chaos. Need help achieving clean one-half columns. Appreciate any assistance! ...

Implementing a callback function following the completion of file reading in Phonegap

I have been facing this issue for quite some time now and I need assistance in finding a solution: When it comes to developing an android app, I rely on the phonegap framework. There is an async function called readFromFile() that reads a json file store ...

The Datejs library is experiencing issues following an upgrade to jQuery 3.x

I'm currently working on a node.js project that utilizes the Datejs library. However, after updating our local jQuery file from version 1.9.1 to 3.6.0, this library has stopped functioning properly. Here is a snippet of the code: var today = Date ...

Confusion arises from conflicting Vue component script indentation guidelines

As I work on setting ESLint rules for my new Vue project, I am extending both eslint-plugin-vue and airbnb. All is well except for one issue - the indentation of the tag inside Vue components. The usual accepted format looks like this: <script> ex ...

Using JavaScript to dynamically load Cascading Style Sheets based on the current

I am trying to dynamically load different CSS files based on the current date (season). I attempted to tweak an image script that I found on Stack Overflow, but it didn't yield the desired result. Could someone please guide me on where I might be ma ...

Using values from a designated line within the textarea to successfully submit a GET form

How can I extract values from a specific line in a TextArea and use them to submit a form? <!DOCTYPE html> <html> <body> <input type='button' value='submit' onclick='document.getElementById("submit-line-3") . ...

What is the preferred convention for defining AngularJS directives as "attributes" versus "elements"?

When creating Angular directives, I've noticed that some directives could also be defined as either an HTML element or an attribute. I'm curious to know what the community convention is for choosing between the two, and the reasons behind it. Fo ...

Ways to retrieve the final appearance of element m in array n

As a beginner in programming, my goal is to access the last position of element m within array n. The following code displays all positions of element m: var n = []; while (true) { let input = prompt("Please enter a number for the ...

How to ensure two unordered lists are aligned at the same baseline using CSS

Is it possible to align two UL's to a single baseline, with one UL aligned flush left and the other flush right? Currently, the UL's are not aligned and appear like this: How can I make sure the two UL's share the same baseline? CSS #foo ...

Exploring the power of ES6 map function within React stateless components

I have a React application that fetches an array of objects from an API response. I want to display each object's details in an accordion format. Using the react-accessible accordion library, I created a React Stateless Component to achieve this. Each ...

Launching a URL in a pop-up window with customized title and address bar

I am seeking to implement a feature similar to the following: <a href="post/23">post 23</a> When a user clicks on this element, I want a popup div to fade in and load the HTML from page post/23 into it. Additionally, I would like the title an ...