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:

<!DOCTYPE HTML>
<html>
<head>
	<script src="jquery-1.9.1.js" type="text/javascript"></script>
	<script src="jquery.metadata.js" type="text/javascript"></script>
	<style>
		.kennykee-styles{
			font-size: 20px; 
			font-family: Arial; 
			margin: 10px; 
			font-weight:bold;
		}
		#main-style, #result-box select{
			font-size: 50px;
			float: left;
		}
	</style>
	<script type="text/javascript">

		$(document).ready(function(){

			$("#main-style").change(function(){
				$("#main-style option:selected").each(function(){
					var colour_data = $(this).metadata();
					if(colour_data.color){
						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").html(selectObj);
						$("#result-box").show("slow");
					}else{
						$("#result-box").hide("slow", function(){
							$("#result-box").html("");
						});
					}
				});				
			});
		});

	</script>
</head>
<body>
	<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>
	</select>

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

</body>
</html>

Demohttp://kennykee.com/demo/dropdown/

One thought on “Update Another Drop Down Options Based On Another Using jQuery

  1. Marissa

    Hi, although the code looks simple and the demo works on your website, it doesnt work if I copy the code and try it. The exact same code. I use dreamweaver. Any suggestions?

    Reply

Leave a Reply

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


three + 6 =