JQuery: Dynamically Injecting Local Data Source (JSON Array) to Dropdown.

If you are a web developer, you might face javasript problem like, when you select one item from dropdown menu, another dropdown displays different type of data (According to the selection, data dynamically changing). So, how we achieve such kind of thing using simple JQuery.You can do the same thing with AngularJS or BackboneJS but here I only show you the simplest JQuery way to solve that.

Here is the Code.

var data = { "Towns":[ "TownA", "TownB", "TownC", "TownD", "TownE" ],
             "Airports":[ "AirportA", "AirportB", "AirportC", "AirportD", "AirportE" ] };

function func1(){

  $( "#choice1" ).change(function (e) {
  
    var choice1_value = $("#choice1")[0].value;
	var choice2 = $('#choice2');
	
	$("#choice2").empty();
	
	$.each(data[choice1_value], function(val, text) {
		choice2.append(
			$('<option></option>').val(val).html(text)
		);
	});
	
  }).change();
}

$(document).ready(function(){
	func1();
});

Make sure your html code as follows.

<html>
<head><title>Change Test</title>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Your script here -->
</head>
<body>
<select id="choice1">
<option id="towns" name="towns" onSelect="func1();">Towns</option>
<option id="airports" name="airports">Airports</option>
</select>
<select id="choice2">
</select>
</body>
</html>