17 Jul, 2009
Dropdown menu population using JSON and jQuery
Web Development » Snippets, Tutorials » Dropdown menu population using JSON and jQuery
This example shows how to populate dropdown menus automatically with values from a JSON object using jQuery. Among other things, it demonstrates:
- How to define a JSON object in Javascript
- How to write a custom function in jQuery using $.fn
- How to traverse a JSON object using jQuery
- How to populate a dropdown menu dynamically using jQuery
Javascript
<script type="text/javascript">
/* <![CDATA[ */
(function($) {
$.fn.changeType = function(){
var data = [
{
"department": "IT",
"jobs": [
{"title":"Programmer"},
{"title":"Solutions Architect"},
{"title":"Database Developer"}
]
},
{"department": "Accounting",
"jobs": [
{"title":"Accountant"},
{"title":"Payroll Officer"},
{"title":"Accounts Clerk"},
{"title":"Analyst"},
{"title":"Financial Controller"}
]
},
{
"department": "HR",
"jobs": [
{"title":"Recruitment Consultant"},
{"title":"Change Management"},
{"title":"Industrial Relations"}
]
},
{
"department": "Marketing",
"jobs": [
{"title":"Market Researcher"},
{"title":"Marketing Manager"},
{"title":"Marketing Co-ordinator"}
]
}
]
var options_departments = '<option>Select<\/option>';
$.each(data, function(i,d){
options_departments += '<option value="' + d.department + '">' + d.department + '<\/option>';
});
$("select#departments", this).html(options_departments);
$("select#departments", this).change(function(){
var index = $(this).get(0).selectedIndex;
var d = data[index-1]; // -1 because index 0 is for empty 'Select' option
var options = '';
if (index > 0) {
$.each(d.jobs, function(i,j){
options += '<option value="' + j.title + '">' + j.title + '<\/option>';
});
} else {
options += '<option>Select<\/option>';
}
$("select#jobs").html(options);
})
};
})(jQuery);
$(document).ready(function() {
$("form#search").changeType();
});
/* ]]> */
</script>
HTML
<form id="search" action="" name="search"> <select name="departments" id="departments"> <option>Select</option> </select> <select name="jobs" id="jobs"> <option>Select</option> </select> </form>








