Senario:

We have few data only and not worthy to create database. Beside data is rarely change. So as alternative, we just can use json as a replacement. Its very easy and straight forward. Without database.

For this exercise, we use state and district selection as example.

First. we need set of json data. Lets say we save as data.js or put directly in the file, which one you prefer

var data={state:[{title:"Selangor",id:1},{title:"Kelantan",id:2},{title:"Terengganu",id:3},{title:"Pahang",id:4},{title:"Johor",id:5}],type:[{title:"Seri Kembangan",id:1},{title:"Sungai Buloh",id:1},{title:"Shah Alam",id:1},{title:"Serdang",id:1},{title:"Tumpat",id:2},{title:"Kota Bharu",id:2},{title:"Gua Musang",id:2},{title:"Kuala Terengganu",id:3},{title:"Dungun",id:3},{title:"Besut",id:3},{title:"Pekan",id:4},{title:"Kuantan",id:4},{title:"Temerloh",id:4},{title:"Segamat",id:5},{title:"Johor Bharu",id:5},{title:"Batu Pahat",id:5}]}

 

Our html

<div>
State
<select id="state"></select>

District
<select id="district"></select>
</div>

 

Our js script. Get state data and push into state drop down menu

for (var i = 0; i < data.state.length; i++) {
$("#state").append("<option value=" + data.state[i].id + ">" + data.state[i].title + "</option>");
}

 

After that, get district base on state id and push into district drop down. Its like a select clause in sql

//get district when state selected
$( "#state" ).change(function() {
$("#district").html("");
var d=($("#state").val());

$.each(data.type, function(i, key) {
if (key.id == d) {
$("#district").append("<option value=" + data.type[i].title + ">" + data.type[i].title + "</option>");
}
});

 

Here are the full code

 

drop down menu with jquery and json
drop down menu
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="data.js"></script>
<script>

$(document).ready(function(){
for (var i = 0; i < data.state.length; i++) {
$("#state").append("<option value=" + data.state[i].id + ">" + data.state[i].title + "</option>");
}

//get district when state selected
$( "#state" ).change(function() {
$("#district").html("");
var d=($("#state").val());

$.each(data.type, function(i, key) {
if (key.id == d) {
$("#district").append("<option value=" + data.type[i].title + ">" + data.type[i].title + "</option>");
}
});
});
});
</script>
</head>
<body>
<div>
State
<select id="state"></select>

District
<select id="district"></select>
</div>
</body>
</html>

 

If you are code in .net, you have alternative to use jslinq (JSON Linq)

Drop down Select With Jquery and Json
Tagged on:     

Leave a Reply

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