Restricting form choices for multi-level child inputs using JavaScript

In my current form, the structure is as follows:

kingdom --> phylum --> class --> order --> family --> genus...

If the kingdom = Animalia, then the options for phylum should be a specific list.

Similarly, if the phylum is set to Chordata, the next dropdown input should have a predefined list of choices.

This pattern continues with conditions based on the values selected in the previous levels, creating a hierarchical form with interdependent levels.

I have explored various examples and attempted to implement them, but I am unable to find a suitable solution. Any thoughts or suggestions would be greatly appreciated.

Below is the HTML code using Bootstrap:

              <div class='col-12 left'>
                <div class='form-group'>
                  <label for='uname'>kingdom</label>
                  <select class="form-control" name='kingdom'>
                    <option>Animalia</option>
                    <option>Plantae</option>
                    <option>Fungi</option>
                    <option>Protista</option>
                    <option>Monera</option>
                  </select>
                  <div class='valid-feedback'>Valid.</div>
                  <div class='invalid-feedback'>Please fill out this field.</div>
                </div>
              </div>

              <div class='col-12 left'>
                <div class='form-group'>
                  <label for='uname'>phylum/division</label>
                  <select class="form-control" name='phylum'>
                    <option>Chordata</option>
                    <option>Annelid</option>
                    <option>Arthropod</option>
                    <option>Bryozoa</option>
                    <option>Cnidaria</option>
                    <option>Echinoderm</option>
                    <option>Mollusc</option>
                    <option>Nematode</option>
                    <option>Platyhelminthes</option>
                    <option>Rotifer</option>
                    <option>Sponge</option>
                  </select>
                // More code here...

Answer №1

Perhaps a tad slothful, yet effective if you find it similar

<div class="form-group" >
    <select class="form-control" id="sel0">
        <option value="0">Pick</option>
        <option value="1">Audi</option>
        <option value="2">BMW</option>
    </select>
    <br>
    <select class="form-control dispnone" id="sel1_1">
        <option value="0">Choose</option>
        <option value="1">A4</option>
        <option value="2">RS8</option>
    </select>
    <select class="form-control dispnone" id="sel1_2">
        <option value="0">Choose</option>
        <option value="1">E36</option>
        <option value="2">X5</option>
    </select>
    <select class="form-control dispnone" id="sel2_1">
        <option value="0">Choose</option>
        <option value="1">120LE</option>
        <option value="2">140LE</option>
    </select>
    <select class="form-control dispnone" id="sel2_2">
        <option value="0">Choose</option>
        <option value="1">cyl8</option>
        <option value="2">cyl16</option>
    </select>

<script type="text/javascript">
    $(document).ready(function() {
        var select_nums = 3;
        $("#sel0").change(function() {
            var ch = $("#sel0").val();
            if(ch==0){
                for (var i = 1; i < select_nums; i++) {
                    $('#sel1_'+i).css({'display':'none'});
                }
                $('#sel1_'+ch).css({'display':'block'});
            }else if(ch==1){
                for (var i = 1; i < select_nums; i++) {
                    $('#sel1_'+i).css({'display':'none'});
                }
                  $('#sel1_'+ch).css({'display':'block'});
            }else if(ch==2){
                for (var i = 1; i < select_nums; i++) {
                    $('#sel1_'+i).css({'display':'none'});
                }
                $('#sel1_'+ch).css({'display':'block'});
            }
        });

        $("#sel1_1").change(function() {
            var ch = $("#sel1_1").val();
            if(ch==0){
                for (var i = 1; i < select_nums; i++) {
                    $('#sel2_'+i).css({'display':'none'});
                }
                $('#sel2_'+ch).css({'display':'block'});
            }else if(ch==1){
                for (var i = 1; i < select_nums; i++) {
                    $('#sel2_'+i).css({'display':'none'});
                }
                $('#sel2_'+ch).css({'display':'block'});
            }else if(ch==2){
                for (var i = 1; i < select_nums; i++) {
                    $('#sel2_'+i).css({'display':'none'});
                }
                $('#sel2_'+ch).css({'display':'block'});
            }
        });

    });
</script>

Answer №2

I managed to extract a segment of your HTML code and make it functional by implementing an event listener to hide the unnecessary options. Here is the solution I came up with:

For demonstration purposes, I focused on displaying only the first two categories - 'Animalia' and 'Plantae', along with two subsets of options for each category. The code includes a change event on the select tag that triggers the hiding and showing functionality as needed.

function hideSubset(selectedValue){
    
    let secondChoice = document.querySelector('#secondChoice');
    let firstChoice = document.querySelector('#firstChoice');

    if (selectedValue === 'Animalia'){
        
        secondChoice.style.display = 'none';
        firstChoice.style.display = 'block';
        
    } else {
        
        firstChoice.style.display = 'none';
        secondChoice.style.display = 'block';
    }
}


let mainChoice = document.querySelector('#mainChoice');

mainChoice.addEventListener('change', function(){
    hideSubset(mainChoice.value);
}, false);
<div class='col-12 left'>
    <div class='form-group'>
      <label for='uname'>kingdom</label>
      <!-- <input type='text' class='form-control' name='kingdom' value ='Animalia' placeholder='Animalia' > -->


      <select class="form-control" name='kingdom' id="mainChoice">
        <option>Choose one</option>
        <option>Animalia</option>
        <option>Plantae</option>   
      </select>
      <div class='valid-feedback'>Valid.</div>
      <div class='invalid-feedback'>Please fill out this field.</div>
    </div>
  </div>

  <div class='col-12 left' id="firstChoice">
    <div class='form-group'>
      <label for='uname'>Options for Animalia</label>
      <!-- <input type='text' class='form-control' name='phylum' value ='Chordata' placeholder='Chordata' > -->
      <select class="form-control" name='phylum'>
        <option>Chordata</option>
        <option>Annelid</option>
        <option>Arthropod</option>
        <option>Bryozoa</option>
        <option>Cnidaria</option>
        <option>Echinoderm</option>

      </select>
      <div class='valid-feedback'>Valid.</div>
      <div class='invalid-feedback'>Please fill out this field.</div>
    </div>
  </div>

  <div class='col-12 left' id="secondChoice">
    <div class='form-group'>
      <label for='uname'>Options for Plantae</label>
      <!-- <input type='text' class='form-control' name='phylum' value ='Chordata' placeholder='Chordata' > -->
      <select class="form-control" name='phylum'>
        <option>Mollusc</option>
        <option>Nematode</option>
        <option>Platyhelminthes</option>
        <option>Rotifer</option>
        <option>Sponge</option>

      </select>
      <div class='valid-feedback'>Valid.</div>
      <div class='invalid-feedback'>Please fill out this field.</div>
    </div>
  </div>

This is how it appears on my end. I utilized Bootstrap 4 for styling.

Screenshot when loading

Screenshot after selecting Animalia

Screenshot after choosing Plantae

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

Troubleshooting JavaScript Object allocation problem

As someone who is not an expert in JavaScript, I have a question that may seem silly. Let's say I have the following snippet of HTML: <div> <script type="text/javascript"> var variable_2 = new SomeObject(); </script ...

Oops! Looks like the connection has been abruptly cut off from the ASYNC node

Is there a way to properly close an async connection once all data has been successfully entered? Despite attempting to end the connection outside of the loop, it seems that the structure is being finalized after the first INSERT operation CODE require( ...

In iOS devices, the Ionic framework restricts the ability to open links in a new tab using the ng-href attribute

In my quest for mobile functionality, I'm aiming to implement a feature on devices where tapping will open 'codepen.io' (triggered by ng-click), and tap and hold will display a context menu with the option to 'Open In New Tab', red ...

"Discovering the method to showcase content based on page number or when the 'previous' or 'next'

Here is how my Vue component looks like: <template> ... <b-col v-for="item in items" v-bind:key="item.id" cols="2"> ... <strong slot="header" class="text-dark" :title ...

Is there a way to disable automatic spacing in VS code for a React file?

I am currently working on my code in VS Code within my JSX file, but I keep encountering an error. The issue seems to be that the closing tag < /h1> is not being recognized. I have attempted multiple methods to prevent this automatic spacing, but so ...

PHP Arrays and HTML Form Select Elements

I am facing a challenge with a form that contains multiple rows and numerous "select" drop-down menus in each row. While I'm presenting a simplified 2x2 example here, the actual form could extend up to 5x5. Here is an outline of my HTML form: <fo ...

"Upload a video file and use JavaScript to extract and save the first frame as an image

I have a webpage where users can upload a video file, and the page will generate a thumbnail based on a timestamp provided by the user. Currently, I am focusing on generating the thumbnail from the FIRST frame of the video. Here is an example of my progr ...

Browser Compatibility with AngularJS

Encountering an issue with AngularJS compatibility - are there any features not supported by Google Chrome? We have developed the AngularUI Calendar and utilized the JSFiddle link below: http://jsfiddle.net/joshkurz/xqjtw/52/ The UI calendar works on Fi ...

Javascript problem involving multiple scopes in closures

What is the most effective solution for addressing this issue related to closure in JavaScript? Here is a simple problem I am facing: I have 10 spans with onclick events (I want an alert showing the number of the span clicked on each click): var spans = ...

Ways to receive attributes prior to the Render event

I am a beginner in React and encountering an issue with retrieving props from the parent before the child is rendered. https://i.sstatic.net/CLAdH.png My problem involves an Editor component that passes a string as props to a button. The string is collect ...

Tips for adding text dynamically to images on a carousel

The carousel I am using is Elastislide which can be found at http://tympanus.net/Development/Elastislide/index.html. Currently, it displays results inside the carousel after a search, but I am struggling to dynamically add text in order to clarify to use ...

Issue with Basic jQuery Demonstration (Failure to Conceal Item)

Below is a jQuery example where an element should be hidden, but it's not working as expected: <html> <head> <script src="../lib/jquery-1.7.1.min.js" type="text/javascript"></script> <script type="text/javascript"> $ ...

What steps can you take to address Git conflicts within the yarn.lock file?

When numerous branches in a Git project make changes to dependencies and use Yarn, conflicts may arise in the yarn.lock file. Instead of deleting and recreating the yarn.lock file, which could lead to unintended package upgrades, what is the most efficie ...

Angular Directive - introducing a fresh approach to two-way binding and enable "pass-by-value" functionality

In a previous question, I inquired about the possibility of incorporating an attribute on a directive to allow for values to be passed in various formats, such as: <my-directive att> //Evaluates to true <my-directive att="true"> ...

Should I use "npm install" or "sudo npm install -g"

When it comes to installing certain packages, sometimes running sudo npm install -g is necessary, while for others simply using npm install is enough. What causes this difference and why does it exist? Take the following examples: npm install -g grunt-c ...

Ensuring the canvas fits perfectly within its parent div

I am attempting to adjust my canvas to fit inside a div. // Make the Canvas Responsive window.onload = function(){ wih = window.innerHeight; wiw = window.innerWidth; } window.onresize = function(){ wih = window.innerHeight; wiw = window.innerWidth; } // ...

I'm curious about integrating Font Awesome into my React.js project - any tips on

I'm having trouble getting Font Awesome to display in my React JS project. Here is the code I am using: import React, {Component} from 'react' import './category.css' import axios from 'axios' import Course from './c ...

html2canvas encountered a CORS error when trying to retrieve images from an external domain

I have been attempting to export a react component as a PDF file. Here are the steps I have followed: Converting the component into an image using html2canvas Creating a PDF document Attaching the image to the PDF The component contains images with URLs ...

When using JavaScript, I have noticed that my incremental pattern is 1, 3, 6, and 10

I am currently using a file upload script known as Simple Photo Manager. Whenever I upload multiple images and wish to delete some of them, I find myself in need of creating a variable called numDeleted (which basically represents the number of images dele ...

Activate audio and trigger notification

I'm looking to incorporate a small beep sound into my web application before displaying an alert message. Here's what I currently have: if(_none_valid) { $.playSound('/static/wav/beep_error.wav').delay(300); alert('ERROR: ...