How to create dynamic drop-down list in javascript depending on each other.Lets see below simple example which has shown two drop down list .One is depending upon the other like second dropdown values will be depend upon the first one.Means If you select any value from first drop-down then you will be getting related dynamic drop down in as a second drop down.

In below example First drop down shows some shorts of language and second will show the related framework of language.For example if you select Java then related framework hibernate and struts will be shown in second drop-down list which generally can created by ajax.But here no ajax has created its only creating values depending upon each other called dependency in javascript.

I have created a function called dynamicdropdown(), which will be called (onchange event) if you change the value of first dropdown list then in that the dynamic dropdown will be created and replace a div and will be shown as second dropdown list.So in this way you can create dynamic drop-down list in javscript.

<script language="javascript" type="text/javascript">
	function dynamicdropdown(listindex)
	{
		document.getElementById("subcategory").length = 0;
		switch (listindex)
		{
			case "Php" :
				document.getElementById("subcategory").options[0]=new Option("Please select framework","");
				document.getElementById("subcategory").options[1]=new Option("Cakephp","Cakephp");
				document.getElementById("subcategory").options[2]=new Option("Wordpress","Wordpress");
				document.getElementById("subcategory").options[3]=new Option("Codeigniter","Codeigniter");
				document.getElementById("subcategory").options[4]=new Option("Joomla","Joomla");
				document.getElementById("subcategory").options[5]=new Option("Magento","Magento");
				break;
			
			case "Java" :
				document.getElementById("subcategory").options[0]=new Option("Please select framework","");
				document.getElementById("subcategory").options[1]=new Option("Strauts","Strauts");
				document.getElementById("subcategory").options[2]=new Option("Hibernate","Hibernate");
				break;
			case "Javascript" :
				document.getElementById("subcategory").options[0]=new Option("Please select framework","");
				document.getElementById("subcategory").options[1]=new Option("D-Jango","D-Jango");
				document.getElementById("subcategory").options[2]=new Option("Angular","Angular");
				document.getElementById("subcategory").options[3]=new Option("Prototype","Prototype");
				document.getElementById("subcategory").options[4]=new Option("jQuery","jQuery");
				document.getElementById("subcategory").options[5]=new Option("Backbone","Backbone");
				break;
			case "Dotnet" :
				document.getElementById("subcategory").options[0]=new Option("Please select framework","");
				document.getElementById("subcategory").options[1]=new Option("VbScript","VbScript");
				break;
		}
		return true;
	}
</script>
<div id="category_div" class="category_div">Please specify language:
	<select id="category" class="required-entry" name="category" onchange="javascript: dynamicdropdown(this.options[this.selectedIndex].value);">
		<option value="">Select Language</option>
		<option value="Php">Php</option>
		<option value="Java">Java</option>
		<option value="Javascript">Javascript</option>
		<option value="Dotnet">Dotnet</option>
	</select>
</div>

<div id="sub_category_div" class="sub_category_div">Please select framework:
	<script type="text/javascript" language="JavaScript">
		document.write('<select name="subcategory" id="subcategory"><option value="">Please select framework</option></select>')
	</script>
	<noscript>
		<select name="subcategory" id="subcategory" >
			<option value="">Please select framework</option>
		</select>
	</noscript>
</div>

Make all above as dynamic by using Mysql Database and PHP:

Below example I have a data base called “test” and has two tables called “language”, “framework”. So I will be going to fetch data from language and will make that as mys first dropdown. Ten I will fetching that data from framework and will make as second dropdown depending upon the changes value of first dropdwon.

Language Table

--
-- Table structure for table `language`
--

CREATE TABLE IF NOT EXISTS `language` (
  `id` int(25) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

--
-- Dumping data for table `language`
--

INSERT INTO `language` (`id`, `name`) VALUES
(1, 'php'),
(2, 'java'),
(3, 'javascript'),
(4, 'dotnet');

Framework Table

--
-- Table structure for table `framework`
--

CREATE TABLE IF NOT EXISTS `framework` (
  `id` int(25) NOT NULL AUTO_INCREMENT,
  `lang_id` int(25) NOT NULL,
  `framework_name` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=13 ;
--
-- Dumping data for table `framework`
--
INSERT INTO `framework` (`id`, `lang_id`, `framework_name`) VALUES
(1, 1, 'wordpres'),
(2, 1, 'magento'),
(3, 2, 'strut'),
(4, 2, 'hibernate'),
(5, 3, 'jquery'),
(6, 3, 'prototype'),
(7, 4, 'vbscript'),
(9, 1, 'cakephp'),
(10, 1, 'joomla'),
(11, 3, 'django'),
(12, 3, 'angular');
<?php
	$servername = "localhost";
	$username = "root";
	$password = "";
	$dbname = "test";
	
	// Create connection
	$conn = new mysqli($servername, $username, $password, $dbname);
	// Check connection
	if ($conn->connect_error) {
		die("Connection failed: " . $conn->connect_error);
	} 
	
	$sql = "SELECT * from language";
	$result = $conn->query($sql);
	
	$sqlFramework = "SELECT * FROM `framework`";
	$resultFramework = $conn->query($sqlFramework);
	$rowFrameworkResult = array();
	if ($resultFramework->num_rows > 0) {
		while($rowFramework = mysqli_fetch_assoc($resultFramework)) {
			$rowFrameworkResult[] = $rowFramework;
		}
	}
?>

<div id="category_div" class="category_div">Please specify language:
	<select id="category" class="required-entry" name="category" onchange="javascript: dynamicdropdown(this.options[this.selectedIndex].value);">
		<option value="">Select Language</option>
		<?php if ($result->num_rows > 0) { >
			<?php while($row = mysqli_fetch_assoc($result)) { >
				<option value="<?php echo $row['id']; >"><?php echo $row['name']; ></option>
			<?php } >
		<?php } >
	</select>
</div>

If you would like to get the full files then click here

Live Demo For Two Dropdown

Click To Run

Live Demo For Three Dropdown

Click To Run

Hope You enjoy this article

create dynamic drop-down list
Tagged on:                 

23 thoughts on “create dynamic drop-down list

  • November 16, 2015 at 7:53 am
    Permalink

    Hi, how can i make a dynamic drop down list but the value are get from database? any idea? The shown above is we get the values from our code, right? so how can i get the value from db according to what I selected in first drop down box. Thanks

    Reply
    • November 21, 2015 at 3:41 pm
      Permalink

      I have updated my post again for giving solution to your query . So please follow up again then you will be getting everything. Also there is link available to download total script. You can use that benefit. Hope you will be getting your solution and never forget to share or like to help others. Thanks

      Reply
  • January 19, 2016 at 7:07 pm
    Permalink

    Hey Jyotiranjan,

    First off thank you a billion times over for this post. I have been searching and searching for a means to do this for a few days now. I am updating my dads family business website and we need to simplify the “parts” section of the business as it is getting too cluttered.

    Now for my questions.

    1. Actually I can skip this question as I just solved it. I was trying to add a 4th drop-down and was having trouble figuring out why it wouldn’t populate. Then I realized I was missing a small section of code from the body section that wasn’t recognizing the options to populate.

     

    2. This second one is a bit more tricky and I am having trouble finding a solution. Basically I need to create a link to a PDF file with the final drop-down selection. I can do this in 1 of 2 ways. Either they select the final drop-down and a button that has currently been greyed out will become clickable, allowing them to download that specific file. For this option though the button will have to dynamically change with the menu selection, but it would only activate and point to files linked to the final drop-down box. The second option (and second preferred) is if when they select the final drop-down item, it automatically downloads that PDF file. I have outlined the flow of an example below so it is easier to understand.

    Select Product
    – Spreaders
    – “other menu items”

    Select Model
    – Elite Model
    – “other menu items”

    Select Size
    – 5000L
    – “other menu items”

    Select Year
    – 1990-2000
    – “other menu items”

    So they would then click on 1990-2000 and get the parts PDF for that specific item. OR there would be a DOWNLOAD button underneath that they could click on to download the 1990-2000 PDF when they have selected that. I prefer the button option so that people don’t accidentally download the wrong year if they click on it.

    Anyways, any help or insight you can provide would be a great help. I have linked the current website (which as I mentioned I am working on the replacement for currently). The “Parts” tab is the one I am looking to replace with this drop-down menu. You can see here the general flow of items.

    Reply
    • January 23, 2016 at 11:02 am
      Permalink

      Suppose you have all pdf files in your server with names like category-subcategory-sub_subcategory-sub_sub_subcategory.pdf and you wanted this file to available for download once user selected all the option then use the below function getDownloadLink for getting download link and that function getDownloadLink would be be called on onchange of last dropdown . that will be by

      function getDownloadLink(){
      		var categoryEle = document.getElementById("category");
      		var categoryValue = categoryEle.value;
      		var category = categoryValue.replace(/\//g, '-');
      		category = category.replace(/ /g, '-');
      		
      		var subcategoryEle = document.getElementById("subcategory");
      		var subcategoryValue = subcategoryEle.value;
      		var subcategory = subcategoryValue.replace(/\//g, '-');
      		subcategory = subcategory.replace(/ /g, '-');
      		
      		var sub_subcategoryEle = document.getElementById("sub_subcategory");
      		var sub_subcategoryValue = sub_subcategoryEle.value;
      		var sub_subcategory = sub_subcategoryValue.replace(/\//g, '-');
      		sub_subcategory = sub_subcategory.replace(/ /g, '-');
      		
      		var sub_sub_subcategoryEle = document.getElementById("sub_sub_subcategory");
      		var sub_sub_subcategoryValue = sub_sub_subcategoryEle.value;
      		var sub_sub_subcategory = sub_sub_subcategoryValue.replace(/\//g, '-');
      		sub_sub_subcategory = sub_sub_subcategory.replace(/ /g, '-');
      		
      		var linkingPdfName = category+'-'+subcategory+'-'+sub_subcategory+'-'+sub_sub_subcategory+'.pdf';
      		var fullLinkName = 'yourServeUrl'+linkingPdfName;
      		var anchorTag = 'Doanload Pdf';
      		
      		document.getElementById('download_div').innerHTML = anchorTag;
      	    }
      
      Reply
      • January 25, 2016 at 12:28 am
        Permalink

        For some reason it is not working for me, would there be a way I could e-mail you the file to take a look at and see where I am missing something? Again though, big help, getting closer and closer to having the website ready for launch so soon enough this will be the last piece to the puzzle.

        Reply
  • January 26, 2016 at 11:50 pm
    Permalink

    This is great! Could you tell me what I would need to do if I wanted the last option linked to a url so when they select the 3rd option they would be redirected to a weblink? Thank you!

    Reply
  • February 5, 2016 at 3:55 am
    Permalink

    I tried the 3 drop down example with states .. cities … trainingcenters… It worked well for 3 states. Later added more states and cities and centers, it was not working for appropriate center… What could be the problem?

    Reply
  • March 30, 2016 at 1:27 pm
    Permalink

    Thanks for this great post.
    I have the following problem:
    In the second dropdrown I have 2 “groups”. Each “group” depends on the value in the first dropdown.
    Group 1 has 4 values, group 2 has 6 values.
    When I choose group 2, then I see the 6 values. But when I choose after that group 1, it also has the values from 5-6 from group 2.
    You know what I mean? The script has to remove the unnecessary values.
    I’ve taken the code from your first code-example.
    Thank you!

    Reply
  • May 25, 2016 at 5:33 pm
    Permalink

    thank you so much for the code.I wanted to know how to apply this in android studio.please tell me am new to using this.

    Reply
  • June 30, 2016 at 3:24 am
    Permalink

    Hi,

    i’am new in php prgraming. And I have a question – how to ouput selected data from drop list to .txt file?

    Reply
    • June 30, 2016 at 7:30 pm
      Permalink

      If you would like to implement in your javascript function then check below code as an example to create .txt file

          set fso = CreateObject("Scripting.FileSystemObject");  
          set s = fso.CreateTextFile("C:\test.txt", True);
          s.writeline("HI");
          s.writeline("Bye");
          s.writeline("-----------------------------");
          s.Close();
      

      or else if you would like to implement in php file the check below code as a example

      $content = "some text here";
      $fp = fopen($_SERVER['DOCUMENT_ROOT'] . "/myText.txt","wb");
      fwrite($fp,$content);
      fclose($fp);
      
      Reply
  • July 7, 2016 at 10:41 am
    Permalink

    Hi there,

    I am trying to use “Three Dropdown (http://www.jyotiranjan.in/livedemo/js/livedemo.php?fn=ceate-dynamic-three-drop-down-list.html)” code.

    But, I am bit straggling to made the last drop down list of item “clickable” when the user click one of the list it will take you to actual url address.

    For example = PHP >> Word pres >> WordPress_version1(clickable link and it will take you to the actual url)
    WordPress_version2 (clickable link and it will take you to the actual url)

    Will you able to assit me in this matter if it is possible? Looking forward to hearing from you. Thanks

    Reply
    • July 9, 2016 at 7:30 pm
      Permalink

      you could call a new function on select of last step the redirect to the url you want to.

      onchange="javascript: urlRedirectTo(this.options[this.selectedIndex].value);"
      function urlRedirectTo(obj)
      {
      	if('wordpress_version1' == obj)
      		window.location = 'https://wordpress.org/download/';
      	if('wordpress_version2' == obj)
      		window.location = 'https://wordpress.org/download/';
      }
      

      Also I have updated the demo page , you can check full code over there .

      ceate dynamic three drop down list demo

      Reply
  • July 26, 2016 at 8:58 am
    Permalink

    Thank you for the brilliant coding, i have to not to display the 2 and 3 dynamic field if i click java on the first select box , how can i achieve that

    Reply
  • October 19, 2016 at 9:31 am
    Permalink

    thanks for sharing a good article

    Reply
  • August 12, 2017 at 10:35 am
    Permalink

    Great tutorial. This is fully informative tutorial about dynamic drop down menu using jQuery. It just made my work easier. This was so easy to follow and exactly what I was looking for.

    Thanks.

    Reply
  • May 26, 2019 at 7:03 am
    Permalink

    Thank you for this tutorial, it is very helpful. I am just wondering if there is a way to make one of the options selected in the second dropdown.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *