[javascript] Drop-down box dependent on the option selected in another drop-down box

I have 2 different SELECT OPTION in a form.

The first one is Source, the second one is Status. I would like to have different OPTIONS in my Status drop-down list depending on the OPTION selected in my Source drop-down.

Source:

<select id="source" name="source">
     <option>MANUAL</option>
     <option>ONLINE</option>
</select>

Status:

<select id="status" name="status">

</select>

Options: - If Source is MANUAL, then Status is OPEN or DELIVERED - If Source is ONLINE, then Status is OPEN or DELIVERED or SHIPPED

My non-working attempt:

            <script>
            $(document).ready(function () {
            var option = document.getElementById("status").options;
            if (document.getElementById('source').value == "MANUAL") {
                $("#status").append('<option>OPEN</option>');
                $("#status").append('<option>DELIVERED</option>');
                }
            if (document.getElementById('source').value == "ONLINE") {
                $("#status").append('<option>OPEN</option>');
                $("#status").append('<option>DELIVERED</option>');
                $("#status").append('<option>SHIPPED</option>');
                }
            });
            </script>

This question is related to javascript jquery html forms drop-down-menu

The answer is


You're better off making two selects and showing one while hiding the other.

It's easier, and adding options to selects with your method will not work in IE8 (if you care).


I hope the following code will help or solve your problem or you think not that understandable visit http://phppot.com/jquery/jquery-dependent-dropdown-list-countries-and-states/.

HTML DYNAMIC DEPENDENT SELECT

<div class="frmDronpDown">
<div class="row">
    <label>Country:</label><br/>
    <select name="country" id="country-list" class="demoInputBox" onChange="getState(this.value);">
    <option value="">Select Country</option>
    <?php
    foreach($results as $country) {
    ?>
    <option value="<?php echo $country["id"]; ?>"><?php echo $country["name"]; ?></option>
    <?php
    }
    ?>
    </select>
</div>
<div class="row">
    <label>State:</label><br/>
    <select name="state" id="state-list" class="demoInputBox">
    <option value="">Select State</option>
    </select>
</div>

GETTING STATES VIA AJAX

<script> function getState(val) { $.ajax({
type: "POST",
url: "get_state.php",
data:'country_id='+val,
success: function(data){
    $("#state-list").html(data);
}
});} </script>

READ STATE DATABASE USING PHP

<?php require_once("dbcontroller.php"); $db_handle = new DBController();if(!empty($_POST["country_id"])) {
$query ="SELECT * FROM states WHERE countryID = '" . $_POST["country_id"] . "'";
$results = $db_handle->runQuery($query); ?> <option value="">Select State</option><?php foreach($results as $state) { ?> <option value="<?php echo $state["id"]; ?>"><?php echo $state["name"]; ?></option><?php } } ?>

    function dropdownlist(listindex)
    {
         document.getElementById("ddlCity").options.length = 0;
         switch (listindex) 
         {
             case "Karnataka":
                     document.getElementById("ddlCity").options[0] = new Option("--select--", "");
                     document.getElementById("ddlCity").options[1] = new Option("Dharawad", "Dharawad");
                     document.getElementById("ddlCity").options[2] = new Option("Haveri", "Haveri");
                     document.getElementById("ddlCity").options[3] = new Option("Belgum", "Belgum");
                     document.getElementById("ddlCity").options[4] = new Option("Bijapur", "Bijapur");

                 break;

             case "Tamilnadu":
                 document.getElementById("ddlCity").options[0] = new Option("--select--", "");
                 document.getElementById("ddlCity").options[1] = new Option("dgdf", "dgdf");
                 document.getElementById("ddlCity").options[2] = new Option("gffd", "gffd");


                 break;
         }

    }

* State: --Select-- Karnataka Tamilnadu Andra pradesh Telngana

    <div>
        <p>

            <label id="lblCt">
            <span class="red">*</span>
                City:</label>
            <select id="ddlCity">
               <!-- <option>--Select--</option>
                <option value="1">Dharawad</option>
                <option value="2">Belgum</option>
                <option value="3">Bagalkot</option>
                <option value="4">Haveri</option>
                <option>Hydrabadh</option>
                <option>Vijat vada</option>-->
            </select>
            <label id="lblCity"></label>
        </p>
    </div>

for this, I have noticed that it far better to show and hide the tags instead of adding and removing them for the DOM. It performs better that way.


I am posting this answer because in this way you will never need any plugin like jQuery and any other, This has the solution by simple javascript.

<html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script language="javascript" type="text/javascript">
    function dynamicdropdown(listindex)
    {
        switch (listindex)
        {
        case "manual" :
            document.getElementById("status").options[0]=new Option("Select status","");
            document.getElementById("status").options[1]=new Option("OPEN","open");
            document.getElementById("status").options[2]=new Option("DELIVERED","delivered");
            break;
        case "online" :
            document.getElementById("status").options[0]=new Option("Select status","");
            document.getElementById("status").options[1]=new Option("OPEN","open");
            document.getElementById("status").options[2]=new Option("DELIVERED","delivered");
            document.getElementById("status").options[3]=new Option("SHIPPED","shipped");
            break;
        }
        return true;
    }
    </script>
    </head>
    <title>Dynamic Drop Down List</title>
    <body>
    <div class="category_div" id="category_div">Source:
        <select id="source" name="source" onchange="javascript: dynamicdropdown(this.options[this.selectedIndex].value);">
        <option value="">Select source</option>
        <option value="manual">MANUAL</option>
        <option value="online">ONLINE</option>
        </select>
    </div>
    <div class="sub_category_div" id="sub_category_div">Status:
        <script type="text/javascript" language="JavaScript">
        document.write('<select name="status" id="status"><option value="">Select status</option></select>')
        </script>
        <noscript>
        <select id="status" name="status">
            <option value="open">OPEN</option>
            <option value="delivered">DELIVERED</option>
        </select>
        </noscript>
    </div>
    </body>
</html>

For more details, I mean to make dynamic and more dependency please take a look at my article create dynamic drop-down list


In this jsfiddle you'll find a solution I deviced. The idea is to have a selector pair in html and use (plain) javascript to filter the options in the dependent selector, based on the selected option of the first. For example:

<select id="continents">
 <option value = 0>All</option>   
 <option value = 1>Asia</option>
 <option value = 2>Europe</option>
 <option value = 3>Africa</option>
</select> 
<select id="selectcountries"></select>

Uses (in the jsFiddle)

 MAIN.createRelatedSelector
     ( document.querySelector('#continents')           // from select element
      ,document.querySelector('#selectcountries')      // to select element
      ,{                                               // values object 
        Asia: ['China','Japan','North Korea',
               'South Korea','India','Malaysia',
               'Uzbekistan'],
        Europe: ['France','Belgium','Spain','Netherlands','Sweden','Germany'],
        Africa: ['Mali','Namibia','Botswana','Zimbabwe','Burkina Faso','Burundi']
      }
      ,function(a,b){return a>b ? 1 : a<b ? -1 : 0;}   // sort method
 );

[Edit 2021] or use data-attributes, something like:

_x000D_
_x000D_
document.addEventListener("change", checkSelect);

function checkSelect(evt) {
  const origin = evt.target;

  if (origin.dataset.dependentSelector) {
    const selectedOptFrom = origin.querySelector("option:checked")
      .dataset.dependentOpt || "n/a";
    const addRemove = optData => (optData || "") === selectedOptFrom 
      ? "add" : "remove";
    document.querySelectorAll(`${origin.dataset.dependentSelector} option`)
      .forEach( opt => 
        opt.classList[addRemove(opt.dataset.fromDependent)]("display") );
  }
}
_x000D_
[data-from-dependent] {
  display: none;
}

[data-from-dependent].display {
  display: initial;
}
_x000D_
<select id="source" name="source" data-dependent-selector="#status">
  <option>MANUAL</option>
  <option data-dependent-opt="ONLINE">ONLINE</option>
  <option data-dependent-opt="UNKNOWN">UNKNOWN</option>
</select>

<select id="status" name="status">
  <option>OPEN</option>
  <option>DELIVERED</option>
  <option data-from-dependent="ONLINE">SHIPPED</option>
  <option data-from-dependent="UNKNOWN">SHOULD SELECT</option>
  <option data-from-dependent="UNKNOWN">MAYBE IN TRANSIT</option>
</select>
_x000D_
_x000D_
_x000D_


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to forms

How do I hide the PHP explode delimiter from submitted form results? React - clearing an input value after form submit How to prevent page from reloading after form submit - JQuery Input type number "only numeric value" validation Redirecting to a page after submitting form in HTML Clearing input in vuejs form Cleanest way to reset forms Reactjs - Form input validation No value accessor for form control TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm" How to implement drop down list in flutter? How can I create a dropdown menu from a List in Tkinter? How can I close a dropdown on click outside? Making a drop down list using swift? HTML: Select multiple as dropdown How to get selected value of a dropdown menu in ReactJS Avoid dropdown menu close on click inside Bootstrap 3 dropdown select How to make a drop down list in yii2? Android custom dropdown/popup menu