Restricting choices once user selects an option (HTML)

Currently, I am faced with a dilemma regarding two sets of options for an HTML form. One set consists of various units (such as cm, in, ft.), while the other set includes different locations. The selection of a unit would restrict certain location options, and vice versa. Is there a way to limit the choices available to users once they have chosen a unit or location?

Unit:
<br>
<select name="unit_input">
    <br>
    <option selected disabled hidden></option>
    <option value="l">League</option>
    <option value="m">Mile</option>
    <option value="ft">Foot</option>
    <option value='m'>Meter</option>
    <option value="st">Stage</option>
    <option value="km">Kilometer</option>
</select>
<br>

Location:
<br>
<select name="nationality_input">
    <br>
    <option selected disabled hidden></option>
    <option value="italian">Italian</option>
    <option value="german">German</option>
    <option value="french">French</option>
    <option value="hungarian">Hungarian</option>
    <option value="british">British</option>
    <option value="swiss">Swiss</option>
    <option value="spanish">Spanish</option>
</select>
<br>
<br>

Answer №1

Of course! You can implement this feature using JavaScript. Here is the codepen link that demonstrates how it can be done: CodePen Example

Make sure to assign an ID to your drop-down list for the script to work correctly.

<!doctype html>
<html>
    <head>
    </head>
    <body>
        Unit:
        <br>
        <select id="unit_input" name="unit_input" onchange="restrictDropDownLists()">
            <option selected disabled hidden></option>
            <option value="l">League</option>
            <option value="m">Mile</option>
            <option value="ft">Foot</option>
            <option value='m'>Meter</option>
            <option value="st">Stage</option>
            <option value="km">Kilometer</option>
        </select>
        <br>
        <br>
        <br>

        Location:
        <br>
        <select id="nationality_input" name="nationality_input" onchange="restrictDropDownLists()">
            <option selected disabled hidden></option>
            <option value="italian">Italian</option>
            <option value="german">German</option>
            <option value="french">French</option>
            <option value="hungarian">Hungarian</option>
            <option value="british">British</option>
            <option value="swiss">Swiss</option>
            <option value="spanish">Spanish</option>
        </select>
        <br>
        <br>
        <script type="text/javascript">
            function restrictDropDownLists(){
                var unit = document.getElementById("unit_input");
                var nationalilty = document.getElementById("nationality_input");

                switch(unit.value){
                    case "m":
                        // Options to hide:
                        nationalilty.options[1].style.display = "none"; // Italian
                        // etc.
                        // Options to show:
                        nationalilty.options[4].style.display = ""; // British
                        // etc.
                        break;
                    // etc.
                }

                switch(nationalilty.value){
                    case "british":
                        // Options to hide:
                        unit.options[6].style.display = "none"; // Kilometer
                        // etc.
                        // Options to show:
                        unit.options[1].style.display = ""; // League
                        // etc.
                    // etc.
                }
            }

            // Call the function on page load as well:
            restrictDropDownLists();
        </script>
    </body>
</html>

Answer №2

One possible way to achieve this using only CSS could be:

#second option { display: none; }
#first:has(> option#a:checked) ~ #second option.a { display: block; }
#first:has(> option#b:checked) ~ #second option.b { display: block; }
#first:has(> option#c:checked) ~ #second option.c { display: block; }
<select id="first">
  <option id="a">a</option>
  <option id="b">b</option>
  <option id="c">c</option>
</select>
<select id="second">
  <option class="a b c">Shown for all options</option>
  <option class="a">Shown when a selected</option>
  <option class="c">Shown when c selected</option>
</select>

Currently, the `:has()` selector is not widely supported across browsers. Alternatively, you can try a workaround in pure CSS or opt for JavaScript which offers more flexibility. However, there are some limitations to consider with the CSS approach:

label:after { content: ''; display: block; }
input[name=second] { display: none; }
input[name=second] + label { display: none; }
#a:checked ~ input[name=second].a { display: inline; }
#a:checked ~ input[name=second].a + label { display: inline; }
#b:checked ~ input[name=second].b { display: inline; }
#b:checked ~ input[name=second].b + label { display: inline; }
#c:checked ~ input[name=second].c { display: inline; }
#c:checked ~ input[name=second].c + label { display: inline; }
<h4>First</h4>
<input id="a" type="radio" name="first" /><label>A</label>
<input id="b" type="radio" name="first" /><label>B</label>
<input id="c" type="radio" name="first" /><label>C</label>
  
<h4>Second</h4>
<input id="d" type="radio" name="second" class="a b c" /><label>Shown for all options</label>
<input id="e" type="radio" name="second" class="a" /><label>Shown when a is selected</label>
<input id="f" type="radio" name="second" class="c" /><label>Shown when c is selected</label>

The main drawback of using the sibling combinator ``~` in this context is that all inputs need to be siblings, impacting layout and functionality. While CSS-only solutions may improve once `:has()` is universally supported, JavaScript remains a more reliable choice for complex form interactions. Forms often benefit from a state-based UI design pattern seen in frameworks like React and Vue, where elements dynamically update based on the user's actions. Considering technologies like Redux for managing state could enhance your interactive form development.

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

Convert your flexible designs into dynamic HTML with our Flex to HTML/A

Looking for a solution to transform Flex code into Html/Ajax code. Most of my Flex code includes datagrids, buttons, and text labels. ...

Creating a Background Image Using CSS3: A Step-by-Step Guide

Hey there! I'm trying to figure out how to recreate the image attached using CSS3. I've tried a few online tools for generating gradients, but no luck so far. :( I have the original image, but I really want to create the background using CSS3 in ...

Enhance a disabled button by incorporating a ripple effect

I've got a button that toggles on and off depending on the required form fields. When it's enabled, clicking it activates a ripple effect. Now I'd like to have the ripple effect even when the button is disabled. I attempted something simila ...

What is the best way to display a div in Chrome without allowing any user interactions?

I currently have a <div> placed on top of my webpage that follows the mouse cursor. Occasionally, users are able to move the mouse quickly enough to enter the tracking <div>. Additionally, this <div> sometimes prevents users from clicking ...

Use CSS media queries to swap out the map for an embedded image

Looking to make a change on my index page - swapping out a long Google Map for an embedded image version on mobile. The map displays fine on desktop, but on mobile it's too lengthy and makes scrolling difficult. I already adjusted the JS setting to "s ...

Disabling an HTML attribute on a button prevents the ability to click on it

In my React application, I have a button component that looks like this: <button onClick={() =>alert('hi')} disabled={true}>test</button> When I removed the disabled attribute from the browser like so: <button disabled>test& ...

Teaching jQuery selectors to detect recently-added HTML elements

Unable to find a solution in the jQuery documentation, I am seeking help here for my specific issue. Embracing the DRY principle, I aim to utilize JavaScript to include a character countdown helper to any textarea element with maxlength and aria-described ...

Is there a way to determine if a parent of my HTML element possesses a CSS class?

Looking at this HTML code snippet - <div id="parent" class="foo"> <div id="child"> </div> </div> Is there a way to create a test to verify if the child element is utilizing the foo class? I attempted: element .children("#chi ...

What is the best way to set up a side-opening feature in the UI design?

I am having trouble with the Amoclan shape transitioning to the next side. I need the transition to occur exactly as specified in the documentation, but for some reason it is still moving on to the next side. <html> <head> <script src=" ...

Leveraging backstretch.js in combination with blur.js (or equivalent)

Query Update I provided a response to the query below, however, I am experiencing some lag and a noticeable stepped transition between images. Can anyone offer advice on how to optimize this issue? Perhaps it would be better to go back to using a static ...

How to horizontally align a logo image in the appBar using Material-UI (ReactJS)

I recently incorporated a Material UI library into my React project (material-ui.com) and I've been trying to center my logo within the appbar component. Here is the code that I attempted: <AppBar position="sticky" > <Toolbar> ...

Tips for setting background colors as a prop for Material UI cards in React JS

Currently utilizing the Material UI next framework to construct a wrapper for the card component. This customized wrapper allows for personalization of the component. I have successfully extended the component so that the title and image within the card ca ...

The value entered is displaying as not defined

As a newcomer to the world of javascript, I am diving into creating a simple To Do list. The basic functionality is there, but I'm scratching my head trying to figure out why the input value in my code keeps returning undefined. The remove button is ...

Reposition icons accordingly while incorporating a new set of icons

After creating a new icon set font, I noticed that the icons are not positioning correctly and appear smaller than expected when loaded: https://i.stack.imgur.com/1OsAL.png https://i.stack.imgur.com/zmLQq.png I attempted to adjust the .icon class by add ...

Navigating Divs Using jQuery

I am working with a class that has multiple divs, each with a unique id attached to it. I am using jQuery to dynamically cycle through these divs. This is a snippet of my HTML code: <div id ="result">RESULT GOES HERE</div> ...

The background image fails to display on the button

Why isn't the background image for my button appearing when set using a CSS rule? I have a button with the class "todo" and although other parts of the rule work, the image itself does not show up even after trying "background: url" and "background-im ...

Tips for centering text on a webpage using the div element in HTML

I need help aligning the text "Monitoring Engineering Dashboard" to the right side of the image in the top-left corner. Currently, it is positioned below the image (Refer to the image below) <div style="width:1200px; margin:0 auto ...

Locating Elements with Python 3 and Selenium: Unraveling the xpath Mystery

https://www.facebook.com/friends/requests/?fcref=jwl&outgoing=1 I am looking to click on the "See more request" option within the "friend request sent" section. <div id="outgoing_reqs_pager_57b87e5793eb04682598549" class="clearfix mtm uiMorePager ...

Creating a visually appealing background image using WordPress and PHP

Currently struggling with adjusting the width of an image that's set as a background in Wordpress. The text is perfectly centered, but the background image remains full size and I want it to match the container size... You can view the image at the t ...

Using jQuery to add a class to an input option if its value exists in an array

Looking for a way to dynamically add a class to select option values by comparing them with an array received from an ajax call. HTML <select id="my_id"> <option value="1">1</option> <option value="2">2</option> ...