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

How do I resolve the issue of unable to align the element correctly?

I am struggling to create a hamburger menu icon and align it using flexbox. Unfortunately, the icon is not aligning properly as it is going beyond the menu and the browser screen with an odd top indent. Below is the code I have written: * { margin: 0 ...

Having trouble with Jquery's Scroll to Div feature?

When I click on the image (class = 'scrollTo'), I want the page to scroll down to the next div (second-container). I've tried searching for a solution but nothing seems to work. Whenever I click, the page just refreshes. Any help would be gr ...

The Slim POST function is not successfully uploading data to MySQL database

I have encountered a strange issue. Despite receiving no errors or console messages, everything appears to return a 200 status successfully. I am utilizing the Slim framework to POST data into my database. When I access existing data via the URL, everythi ...

What could be the reason for ThemeProvider (Material UI) failing to function properly in this scenario?

I've encountered something puzzling with Material UI. Despite my experience with it, I can't seem to figure out why my H2 tag in the nested component is rendering in Times instead of Arial. I've double-checked the docs and my code, but the i ...

Issue encountered when concealing page elements followed by revealing them again

My goal is to conceal an id within a page and then reveal it once all the JavaScript has finished loading on the page. The JavaScript I am using to display the content again is: $(document).ready(function() { $("#HomePage")[0].style.visibility = "visib ...

Tips for creating a vertical Angular Material slider with CSS

Attempting to modify the angular material directive to render vertically has been a challenge. I experimented with using transform:rotate in the CSS, however, it resulted in the slider behaving and rendering differently. md-slider { position: absolute ...

The jquery script for the dynamic remove button is malfunctioning

I have successfully implemented code to display dynamic controls using jQuery. Below is the working code: <script type="text/javascript"> $(document).ready(function() { $("input[value='Add']").click(function(e){ e. ...

Unable to select image inside linked container

I'm attempting to display a dropdown menu when the user clicks on the gear-img div using jQuery. However, because it's wrapped inside an a tag, clicking redirects me to a URL. I also want the entire div to be clickable. Any suggestions for a solu ...

displaying a video within an iframe without occupying the entire screen

After successfully implementing a fullscreen video background using the "video" tag with a video hosted on my own server, I decided to switch it out for a Vimeo video. However, after making the necessary code and CSS changes, the video now appears like thi ...

Python Selenium Timeout Exception Handling

Looking for a solution: def get_info(url): options = webdriver.ChromeOptions() options.headless = True chrome_browser = webdriver.Chrome('./chromedriver', chrome_options=options) chrome_browser.get(url) name = chrome_browser.f ...

Attempting to create a child process within the renderer by triggering it with a button click

I'm currently developing an electron application where I am attempting to initiate a child node process (specifically to run a Discord.JS bot). Below is the code snippet in question: index.html: <tr> <th class="title-bar-cell" ...

The expansion feature of PrimeNG Turbotable

I'm currently facing an issue with the Primeng Turbotable where I am unable to expand all rows by default. You can find a code example of my problem at this link. I have already tried implementing the solution provided in this example, but unfortuna ...

Utilize a custom endpoint for Microsoft Graph Toolkit: "Implement a domain-specific endpoint"

I'm currently following the instructions provided at this Microsoft Graph Toolkit tutorial. My code is quite straightforward, including the script reference, the mgt-msal2-provider element with my client-id specified, and a basic login component < ...

Adjust the Bootstrap flex settings to display only 3 cards instead of the default 4 cards - HTML

We currently have a bootstrap setup that displays 4 horizontal scroll cards by default. However, we are looking to only show 3 cards in view and allow the 4th card to be viewed by scrolling. Code On mobile view, the code is still displaying 4 tiles even ...

Storing client-requested data locally

Is it possible to use JavaScript to make an AJAX request to fetch data from a server, then prompt the user to save this data on their computer for later access outside of the browser session? Can this saving functionality be achieved without using a Flas ...

What is the process for clicking on the second link within a table when the values are constantly changing in Selenium RC Server?

How can I click on the second link labeled XYZ STORES? How do I print the text "Store XYZ address"? How can I click on the second link ABC STORES? How do I print the text "Store ABC address"? The links, addresses, and store names are all changing dynam ...

Guide to adding a new Vue-Grid-Item with a button

Currently, I am working on a software project for the Research department at my university, specifically focusing on an Atomic Layer Deposition system. The main goal of this program is to allow users to create and customize their own 'recipe' for ...

Show a grid layout with adjustable sizing and elements centered in the middle

When dealing with a layout like the one below, how can we ensure that elements are centered within the wrap container? The margins around the elements should be flexible but at least 14px. .wrap{ display: grid; grid-template-columns: repeat(auto-fi ...

Tips on adjusting the default width of the React player interface

I'm currently utilizing react-player to display a video in my app. The default width it comes with is not responsive, and applying CSS didn't prove to be effective. import ReactPlayer from 'react-player'; <ReactPlayer url="https:// ...

Changing the position from fixed to static

It's strange, but for some reason when I attempt to apply position:fixed using jQuery: $('#footer').css('cssText', 'position:fixed !important;'); to my footer, the result on the page is different: <div id="footer" ...