Update Another Drop Down Options Based On Another Using jQuery

Changing a drop down options list based on another selected drop down is easy by using jQuery framework. See demo below:

Demo: http://kennykee.com/demo/dropdown/

Note that there are 2 ways to achieve this. First is to use jQuery framework and jQuery Metadata plugin. Second method is to use HTML5 “data-” attribute. This post will show you the jQuery method.

Explanation of concept
For each <option> tag, we add in metadata. For example

<option class=”option_data {color:’blue,green’}”>Colour Style 1</option>

The data is inserted into the curly bracket next to option_data class. Using jQuery metadata plugin, we can retrieve the “color” variable data. The data will be “blue,green”. Next, we convert this comma separated data into an array by using JavaScript split function. Now, we can create a new drop down with option data using metadata retrieved. We can create new drop down using jQuery. See code example below:

Full Code:

	<script src="jquery-1.9.1.js" type="text/javascript"></script>
	<script src="jquery.metadata.js" type="text/javascript"></script>
			font-size: 20px; 
			font-family: Arial; 
			margin: 10px; 
		#main-style, #result-box select{
			font-size: 50px;
			float: left;
	<script type="text/javascript">


				$("#main-style option:selected").each(function(){
					var colour_data = $(this).metadata();
						var color = colour_data.color;
						var selectObj = $("<select></select>");
						var colorArray = color.split(",");
						for(var i = 0; i < colorArray.length; i++){
							selectObj.append("<option value='" + colorArray[i] + "'>" + colorArray[i] + "</option>");
						$("#result-box").hide("slow", function(){

	<div class="kennykee-styles"><a href="http://kennykee.com">KennyKee Styles</a></div>
	<select id="main-style">
		<option>--Please Select--</option>
		<option class="option_data {color:'blue,green'}">Colour Style 1</option>
		<option class="option_data {color:'red,white'}">Colour Style 2</option>

	<div id="result-box" ></div>



Leave a Reply

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

3 + four =