I have 3 dependent JSON files that are related together, which are countries.json, states.json and cities.json and i want to fill 3 dropdowns select box with those json files i have. For the first time i select a country in the first dropdown, i see its states in the second dropdown but the problem comes when i select another country, its states come with the states of the previous selected country.
$(document).ready(function(){
var countryOptions = '';
var stateOptions = '';
var cityOptions = '';
$.getJSON('countries.json', function(data){
countryOptions += '<option value="">Select country</option>';
$.each(data, function(key, country){
countryOptions += '<option value="'+country.id+'">'+country.name+'</option>';
});
$('#country').html(countryOptions);
});
$(document).on('change', '#country', function(){
var country_id = $(this).val();
if(country_id != '')
{
$.getJSON('states.json', function(data){
stateOptions += '<option value="">Select state</option>';
$.each(data, function(key, state){
if(country_id == state.country_id)
{
stateOptions += '<option value="'+state.id+'">'+state.name+'</option>';
}
});
$('#state').html(stateOptions);
});
}
else
{
$('#state').html('<option value="">Select state</option>');
$('#city').html('<option value="">Select city</option>');
}
});
$(document).on('change', '#state', function(){
var state_id = $(this).val();
if(state_id != '')
{
$.getJSON('cities.json', function(data){
cityOptions += '<option value="">Select city</option>';
$.each(data, function(key, city){
if(state_id == city.state_id)
{
cityOptions += '<option value="'+city.id+'">'+city.name+'</option>';
}
});
$('#city').html(cityOptions);
});
}
else
{
$('#city').html('<option value="">Select city</option>');
}
});
});
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container" style="width:600px;">
<h2 align="center">JSON - Dynamic Dependent Dropdown List using Jquery and Ajax</h2><br /><br />
<select name="country" id="country" class="form-control input-lg">
<option value="">Select country</option>
</select>
<br />
<select name="state" id="state" class="form-control input-lg">
<option value="">Select state</option>
</select>
<br />
<select name="city" id="city" class="form-control input-lg">
<option value="">Select city</option>
</select>
</div>
//countries.json
[
{
"id":"1",
"name":"USA"
},
{
"id":"2",
"name":"Canada"
},
{
"id":"3",
"name":"Australia"
}
]
//states.json
[
{
"id":"4",
"name":"New York",
"country_id":"1"
},
{
"id":"5",
"name":"Alabama",
"country_id":"1"
},
{
"id":"6",
"name":"California",
"country_id":"1"
},
{
"id":"7",
"name":"Ontario",
"country_id":"2"
},
{
"id":"8",
"name":"British Columbia",
"country_id":"2"
},
{
"id":"9",
"name":"New South Wales",
"country_id":"3"
},
{
"id":"10",
"name":"Queensland",
"country_id":"3"
}
]
//cities.json
[
{
"id":"11",
"name":"New York city",
"state_id":"4"
},
{
"id":"12",
"name":"Buffalo",
"state_id":"4"
},
{
"id":"13",
"name":"Albany",
"state_id":"4"
},
{
"id":"14",
"name":"Birmingham",
"state_id":"5"
},
{
"id":"15",
"name":"Montgomery",
"state_id":"5"
},
{
"id":"16",
"name":"Huntsville",
"state_id":"5"
},
{
"id":"17",
"name":"Los Angeles",
"state_id":"6"
},
{
"id":"18",
"name":"San Francisco",
"state_id":"6"
},
{
"id":"19",
"name":"San Diego",
"state_id":"6"
},
{
"id":"20",
"name":"Toronto",
"state_id":"7"
},
{
"id":"21",
"name":"Ottawa",
"state_id":"7"
},
{
"id":"22",
"name":"Vancouver",
"state_id":"8"
},
{
"id":"23",
"name":"Victoria",
"state_id":"8"
},
{
"id":"24",
"name":"Sydney",
"state_id":"9"
},
{
"id":"25",
"name":"Newcastle",
"state_id":"9"
},
{
"id":"26",
"name":"City of Brisbane",
"state_id":"10"
},
{
"id":"27",
"name":"Gold Coast",
"state_id":"10"
}
]
How to solve this problem? i have tried so far, i think the error is in the JQuery loop function $.each(data, function(key, state){});
$.getJSON('states.json', function(data){
stateOptions +=
This is appending to your existing data when you get new data. Change it to this:
$.getJSON('states.json', function(data){
stateOptions =
$(document).ready(function(){
var countryOptions = '';
var stateOptions = '';
var cityOptions = '';
$.getJSON('countries.json', function(data){
countryOptions += '<option value="">Select country</option>';
$.each(data, function(key, country){
countryOptions += '<option value="'+country.id+'">'+country.name+'</option>';
});
$('#country').html(countryOptions);
});
$(document).on('change', '#country', function(){
var country_id = $(this).val();
if(country_id != '')
{
$.getJSON('states.json', function(data){
stateOptions = '<option value="">Select state</option>';
$.each(data, function(key, state){
if(country_id == state.country_id)
{
stateOptions += '<option value="'+state.id+'">'+state.name+'</option>';
}
});
$('#state').html(stateOptions);
});
}
else
{
$('#state').html('<option value="">Select state</option>');
$('#city').html('<option value="">Select city</option>');
}
});
$(document).on('change', '#state', function(){
var state_id = $(this).val();
if(state_id != '')
{
$.getJSON('cities.json', function(data){
cityOptions += '<option value="">Select city</option>';
$.each(data, function(key, city){
if(state_id == city.state_id)
{
cityOptions += '<option value="'+city.id+'">'+city.name+'</option>';
}
});
$('#city').html(cityOptions);
});
}
else
{
$('#city').html('<option value="">Select city</option>');
}
});
});
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container" style="width:600px;">
<h2 align="center">JSON - Dynamic Dependent Dropdown List using Jquery and Ajax</h2><br /><br />
<select name="country" id="country" class="form-control input-lg">
<option value="">Select country</option>
</select>
<br />
<select name="state" id="state" class="form-control input-lg">
<option value="">Select state</option>
</select>
<br />
<select name="city" id="city" class="form-control input-lg">
<option value="">Select city</option>
</select>
</div>
Note The code snippet is just for OPs sake. It won't run because it utilizes Get requests.
Related
I have a script that populates the state dropdown based on country id and while everything is working great I can only save the countries dropdown option on page reload but not the state option using html localStorage.
Here is my code:
$(document).ready(function() {
var country_id = null;
var state_id = null;
$('#country').select2();
$('#state').select2();
$('#city').select2();
$('select[name="country"]').on('change', function() {
var country_id = $(this).val();
if (country_id) {
$.ajax({
url: "/world/getStates.php",
type: "GET",
data: {
'country_id': country_id
},
dataType: "json",
success: function(data) {
$('select[name="state"]').empty();
$('select[name="city"]').empty();
$('select[name="state"]').append('<option value="">Select State</option>');
$.each(JSON.parse(data), function(key, value) {
$('select[name="state"]').append('<option value="' + value.id + '">' + value.name + '</option>');
});
}
});
} else {
$('select[name="state"]').empty();
}
});
$('select[name="state"]').on('change', function() {
var country_id = $('#country').val();
var state_id = $(this).val();
if (state_id) {
$.ajax({
url: "/world/getCities.php",
type: "GET",
data: {
'country_id': country_id,
'state_id': state_id
},
dataType: "json",
success: function(data) {
$('select[name="city"]').empty();
$('select[name="city"]').append('<option value="">Select City</option>');
$.each(JSON.parse(data), function(key, value) {
$('select[name="city"]').append('<option value="' + value.id + '">' + value.name + '</option>');
});
}
});
} else {
$('select[name="city"]').empty();
}
});
$('#country').val("value from localStorage").trigger('change');
$('#state').val("value from localStorage").trigger('change');
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>
<label for="country">Country</label>
<select class="csc-select" name="country" id="country">
<option value="">Select Country</option>
<option>Australia</option>
<option>Denmark</option>
<option>Japan</option>
<option>Norway</option>
<option>Switzerland</option>
</select>
<label for="state">State</label>
<select class="csc-select" name="state" id="state">
<option value="">Select State</option>
</select>
<label for="city">City</label>
<select class="csc-select" name="city" id="city">
<option value="">Select City</option>
</select>
So when I call this after the first on change for the country select, it selects the country based on the localStorage value and triggers the change but it does not do the same for the state, any ideas what I am missing here?
Your options inside state dropdown is loaded after the ajax success is executed so your other code doesn't wait for that and .val() fired before only that's the reason the value is not marked as selected inside state dropdown. Now , to fix this you can move that part inside success function of ajax and then call your change event after the options are appended inside state dropdown.
Demo Code :
$(document).ready(function() {
var country_id = 1 //localStorage.getItem("select2CountryValue");
var state_id = 3 //localStorage.getItem("select2StateValue");
var page_load = true; //added this
var data = [{
"id": 1,
"name": "xyz_State1"
}, {
"id": 2,
"name": "xyz_State2"
}, {
"id": 3,
"name": "xyz_State3"
}] //this is just the demo datas
$('#country').select2();
$('#state').select2();
$('select[name="country"]').on('change', function() {
var country_id = $(this).val();
//localStorage.setItem("select2CountryValue", country_id);
if (country_id) {
/*$.ajax({
url: "/world/getStates.php",
type: "GET",
data: {
'country_id': country_id
},
dataType: "json",
success: function(data) {
console.log(data);
$('select[name="city"]').empty();*/
$('select[name="state"]').empty();
$('select[name="state"]').append('<option value="">Select State</option>');
$.each(data, function(key, value) {
$('select[name="state"]').append('<option value="' + value.id + '">' + value.name + '</option>');
});
//check if the change is called on page load
if (page_load == true) {
$('#state').val(state_id).trigger('change'); //assign slected value after elemnt option is added in dom
page_load = false; //add this so that next time this doesn't get execute
}
/* }
});*/
} else {
$('select[name="state"]').empty();
}
});
$('#country').val(country_id).trigger('change');
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css" />
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.full.min.js"></script>
<p>
<span>Country</span>
<select class="csc-select" name="country" id="country">
<option value="">Select Country</option>
<option value="1">
xyz
</option>
<option value="2">
xyz2
</option>
</select>
</p>
<p>
<span>State</span>
<select class="csc-select" name="state" id="state">
<option value="">Select State</option>
</select>
</p>
when I call this after the first on change for the country select, it selects the country based on the localStorage value and triggers the change but it does not do the same for the state, any ideas what I am missing here?
When you trigger the change event for your #country list, the list of countries already contains values.
When you trigger the change event for your #state list immediately after that, the list is still empty. There can't be any value selected, so the change event does nothing.
You need to wait until the state list is populated, and then trigger the change event.
// this works immediately, because there are countries in your HTML
$('#country').val("value from localStorage").trigger('change');
// this needs to happen in the `success` callback of country Ajax call
$('#state').val("value from localStorage").trigger('change');
The alternative is that you create a temporary option first:
$('#state').append("temporary <option> created from localStorage");
$('#state').val("value from localStorage").trigger('change');
This way you would not have to wait.
That being said, Select2 supports remote data, you don't have to write the Ajax requests or the <option> creation yourself.
$("#country").select2({
ajax: {
url: "/world/getCountries.php"
},
placeholder: 'Pick a country',
minimumInputLength: 1
}).change(function () {
$("#state").val("").trigger("change");
});
$("#state").select2({
ajax: {
url: "/world/getStates.php",
data: (params) => {
// add selected country ID to URL params
params.country_id = $("#country").val();
return params;
}
},
placeholder: 'Pick a state',
minimumInputLength: 1
});
// initialize selection from previous state...
$("#country").append('<option value="5">Switzerland</option>');
$("#country").val("5");
$("#state").append('<option value="9">Appenzell</option>');
$("#state").val("9");
// server side mock-up -------------------------------------------------
const countries = [
{id: 1, text: 'Australia'},
{id: 2, text: 'Denmark' },
{id: 3, text: 'Japan'},
{id: 4, text: 'Norway'},
{id: 5, text: 'Switzerland'}
];
const states = [
{id: 1, text: 'New South Wales', country_id: 1},
{id: 2, text: 'Victoria', country_id: 1},
{id: 3, text: 'Hovedstaden', country_id: 2},
{id: 4, text: 'Midtjylland', country_id: 2},
{id: 5, text: 'Hokkaido', country_id: 3},
{id: 6, text: 'Shikoku', country_id: 3},
{id: 7, text: 'Northern Norway', country_id: 4},
{id: 8, text: 'Southern Norway', country_id: 4},
{id: 9, text: 'Appenzell', country_id: 5},
{id: 10, text: 'Zürich', country_id: 5},
];
$.mockjaxSettings.logging = 1;
$.mockjax({
url: "/world/getCountries.php",
contentType: "application/json",
response: function(settings) {
this.responseText = {
results: countries.filter(item =>
!settings.data.term || item.text.toLowerCase().includes(settings.data.term.toLowerCase())
)
};
}
});
$.mockjax({
url: "/world/getStates.php",
contentType: "application/json",
response: function(settings) {
console.log(settings.data);
this.responseText = {
results: states.filter(item =>
item.country_id == settings.data.country_id && (
!settings.data.term || item.text.toLowerCase().includes(settings.data.term.toLowerCase())
)
)
};
}
});
select {
width: 200px;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-mockjax/2.6.0/jquery.mockjax.min.js"></script>
<select id="country"></select>
<select id="state"></select>
I want to get the JSON from an array with this format
[
{
"title": "Name"
},
{
"title": "Phone"
},
{
"title": "Parent Phone"
},
{
"title": "Street"
}
]
I tried this code:
var favorite = new Array();
$.each($("#db_fields"), function() {
var field = {
'title': $(this).val()
};
favorite.push(field);
});
var myJsonString = JSON.stringify(favorite);
alert(myJsonString);
$("#db_fields") is a select (Bootstrap-select), it's an array of string
<select class="form-control" name="db_fields[]" id="db_fields" data-live-search="true" multiple >
<option value="Arabic Name"> Arabic Name</option>
<option value="Building"> Building</option>
</select>
but I got this result
[{"title":["Arabic Name","Phone","Building","Nationality"]}]
Iterate through the options of the select ("#db_fields > option") tag:
var favorite = [];
$.each($("#db_fields > option"), function(){
let field = {
'title': this.value
};
favorite.push(field);
});
var myJsonString = JSON.stringify(favorite);
console.log(myJsonString);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="form-control" name="db_fields[]" id="db_fields" data-live-search="true" multiple >
<option value="Arabic Name"> Arabic Name</option>
<option value="Building"> Building</option>
</select>
i have json like this
{
"id":"1",
"name":"Kitchen Set",
"parent_id":"0",
},
{
"id":"2",
"name":"Bedroom",
"parent_id":"0"
},
{
"id":"3",
"name":"Living Room",
"parent_id":"0"
},
{
"id":"4",
"name":"Kitchen Set",
"parent_id":"1",
"price":"1000"
},
{
"id":"5",
"name":"Meja Bar",
"parent_id":"1",
"price":"2000"
},
and i want to add price: to my javascript
here is my question i want to get the price from my json to my javascript how can i do that??
i try this but it doesnt work
load_json_data('Price');
function load_json_data(price)
{
var html_code = '';
$.getJSON('int_fur_fin.json', function(data)
}
and this is my javascript
<script>
$(document).ready(function(){
load_json_data('Interior');
function load_json_data(id, parent_id)
{
var html_code = '';
$.getJSON('int_fur_fin.json', function(data){
html_code += '<option value="">Select '+id+'</option>';
$.each(data, function(key, value){
if(id == 'Interior')
{
if(value.parent_id == '0')
{
html_code += '<option value="'+value.id+'">'+value.name+'</option>';
}
}
else
{
if(value.parent_id == parent_id)
{
html_code += '<option value="'+value.id+'">'+value.name+'</option>';
}
}
});
$('#'+id).html(html_code);
});
}
$(document).on('change', '#Interior', function(){
var Interior_id = $(this).val();
if(Interior_id != '')
{
load_json_data('Furniture', Interior_id);
}
else
{
$('#Furniture').html('<option value="">Select Furniture</option>');
}
});
});
</script>
i use this javascript code to populate my dropdown
<form>
<select name="Interior Details" id="Interior" class="form-control input-lg">
<option value="">Select Interior Details</option>
</select>
<br />
<select name="Furniture" id="Furniture" class="form-control input-lg" required >
<option value="">Select Furniture</option>
</select>
</form>
You can use array.find() method to find the matching element. Also i have modified your JSON as a array.
items.find(t=>t.parent_id ==='1');
DEMO
var items = [{
"id":"1",
"name":"Kitchen Set",
"parent_id":"0",
},
{
"id":"2",
"name":"Bedroom",
"parent_id":"0"
},
{
"id":"3",
"name":"Living Room",
"parent_id":"0"
},
{
"id":"4",
"name":"Kitchen Set",
"parent_id":"1",
"price":"1000"
},
{
"id":"5",
"name":"Meja Bar",
"parent_id":"1",
"price":"2000"
}];
var result = items.find(t=>t.parent_id ==='1');
console.log(result);
EDIT
If you want multiple elements with matching id use array.filter.
var items = [{
"id":"1",
"name":"Kitchen Set",
"parent_id":"0",
},
{
"id":"2",
"name":"Bedroom",
"parent_id":"0"
},
{
"id":"3",
"name":"Living Room",
"parent_id":"0"
},
{
"id":"4",
"name":"Kitchen Set",
"parent_id":"1",
"price":"1000"
},
{
"id":"5",
"name":"Meja Bar",
"parent_id":"1",
"price":"2000"
}];
var result = items.filter(t=>t.parent_id ==='1');
console.log(result);
I am working on a form that has multiple SELECT boxes. When a user selects an option from selectbox1, I need another value of selectbox2 active. Likewise when he selects another value of selectbox2, I need another value of selectbox3 active.
Select Region
<select name='region'>
<option value='nw'>North West</option>
<option value='sw'>South West</option>
<option value='w'>West</option>
</select>
<br />
Select Quarter
<select name='quarter'>
<option value='bda'>Bamenda</option>
<option value='man'>Mankon</option>
<option value='ndop'>Ndop</option>
</select>
<br />
Select Area
<select name='area'>
<option value='ba'>Bambili</option>
<option value='bi'>Bambui</option>
<option value='cc'>CCk</option>
</select>
<br />
When a user selects NORTH WEST, let BAMENDA be selected on the next select box.
Add an onchange function to the select in HTML, and the javascript function below.
function updateSelect(id) {
var index = document.getElementById(id).selectedIndex;
document.getElementById("region").selectedIndex = index;
document.getElementById("quarter").selectedIndex = index;
document.getElementById("area").selectedIndex = index;
}
Select Region
<select name='region' id='region' onchange='updateSelect("region")'>
<option value='nw'>North West</option>
<option value='sw'>South West</option>
<option value='w'>West</option>
</select>
<br />
Select Quarter
<select name='quarter' id='quarter' onchange='updateSelect("quarter")'>
<option value='bda'>Bamenda</option>
<option value='man'>Mankon</option>
<option value='ndop'>Ndop</option>
</select>
<br />
Select Area
<select name='area' id='area' onchange='updateSelect("area")'>
<option value='ba'>Bambili</option>
<option value='bi'>Bambui</option>
<option value='cc'>CCk</option>
</select>
In my opinion you should load that metadata from somewhere on demand, but if you are fine with static arrays, I made an example fiddle that will work just fine:
Cascaded selection example
loadQuarters = function () {
var selectRegion = document.getElementById("selectRegion");
var selectedRegionValue = selectRegion.options[selectRegion.selectedIndex].value;
resetSelectQuarter();
var allowedQuarters = quarters[selectedRegionValue];
allowedQuarters.forEach(function(quarter) {
var selectQuarter = document.getElementById("selectQuarter");
var optionQuarter = document.createElement("option");
optionQuarter.text = quarter.label;
optionQuarter.value = quarter.value;
selectQuarter.add(optionQuarter);
});
}
loadAreas = function () {
var selectQuarter = document.getElementById("selectQuarter");
var selectedQuarterValue = selectQuarter.options[selectQuarter.selectedIndex].value;
resetSelectArea();
var allowedAreas = areas[selectedQuarterValue];
allowedAreas.forEach(function(area) {
var selectArea = document.getElementById("selectArea");
var optionArea = document.createElement("option");
optionArea.text = area.label;
optionArea.value = area.value;
selectArea.add(optionArea);
});
}
resetSelectArea = function() {
var selectArea = document.getElementById("selectArea");
removeOptions(selectArea);
var optionArea = document.createElement("option");
optionArea.text = "Select an area";
optionArea.value = null;
selectArea.add(optionArea);
}
resetSelectQuarter = function() {
var selectQuarter = document.getElementById("selectQuarter");
removeOptions(selectQuarter);
var optionQuarter = document.createElement("option");
optionQuarter.text = "Select a quarter";
optionQuarter.value = null;
selectQuarter.add(optionQuarter);
}
removeOptions = function(selectbox) {
var i;
for(i=selectbox.options.length-1;i>=0;i--)
{
selectbox.remove(i);
}
}
regions = {
"nw": {
value: "nw",
label: "North West"
},
"sw": {
value: "sw",
label: "South West"
},
"w": {
value: "w",
label: "West"
}
};
quarters = {
"nw" : [
{
value: "bda",
label: "Bamenda"
}
],
"sw" : [
{
value: "man",
label: "Mankon"
}
],
"w" : [
{
value: "ndop",
label: "Ndop"
}
]
};
areas = {
"bda" : [
{
value: "ba",
label: "Bambili"
}
],
"man" : [
{
value: "bi",
label: "Bambui"
}
],
"ndop" : [
{
value: "cc",
label: "CCk"
}
]
};
Select Region
<select name='region' id="selectRegion" onChange="loadQuarters()">
<option> Select a region </option>
<option value='nw'>North West</option>
<option value='sw'>South West</option>
<option value='w'>West</option>
</select>
<br />
Select Quarter
<select name='quarter' id="selectQuarter" onChange="loadAreas()">
<option> Select a quarter </option>
</select>
<br />
Select Area
<select name='area' id="selectArea">
<option> Select an area </option>
</select>
<br />
How do I only display certain options depending on the value in a select tag?
function key(id){
var selectValue = document.getElementById('names').value
= document.carmakes.cars.selectedIndex
var selectOption = $("#names option:selected").val();
}
<select size='5' name='carmakes' onchange='key(id)'>
<option selected='selected' value="-1">Car makes</option>
<option>BMW</option>
<option>Audi</option>
</select>
<select required='required' size='5' type='text' id='names'>
<option selected="selected" value="0" >Car names</option>
<option value="1">X5</option>
<option value="2">Q5</option>
check this: http://www.sanwebe.com/2013/05/select-box-change-dependent-options-dynamically
<!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8' />
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function(){
//let's create arrays
var chocolates = [
{display: "Dark chocolate", value: "dark-chocolate" },
{display: "Milk chocolate", value: "milk-chocolate" },
{display: "White chocolate", value: "white-chocolate" },
{display: "Gianduja chocolate", value: "gianduja-chocolate" }];
var vegetables = [
{display: "Broccoli", value: "broccoli" },
{display: "Cabbage", value: "cabbage" },
{display: "Carrot", value: "carrot" },
{display: "Cauliflower", value: "cauliflower" }];
var icecreams = [
{display: "Frozen yogurt", value: "frozen-yogurt" },
{display: "Booza", value: "booza" },
{display: "Frozen yogurt", value: "frozen-yogurt" },
{display: "Ice milk", value: "ice-milk" }];
//If parent option is changed
$("#parent_selection").change(function() {
var parent = $(this).val(); //get option value from parent
switch(parent){ //using switch compare selected option and populate child
case 'chocolates':
list(chocolates);
break;
case 'vegetables':
list(vegetables);
break;
case 'icecreams':
list(icecreams);
break;
default: //default child option is blank
$("#child_selection").html('');
break;
}
});
//function to populate child select box
function list(array_list)
{
$("#child_selection").html(""); //reset child options
$(array_list).each(function (i) { //populate child options
$("#child_selection").append("<option value=\""+array_list[i].value+"\">"+array_list[i].display+"</option>");
});
}
});
</script>
</head>
<body>
<div class="wrapper">
Category : <select name="parent_selection" id="parent_selection">
<option value="">-- Please Select --</option>
<option value="chocolates">Chocolates</option>
<option value="vegetables">Vegetables</option>
<option value="icecreams">Ice cream</option>
</select>
<select name="child_selection" id="child_selection">
</select>
</div>
</body>
</html>
or this: http://simpleweb.github.io/jquery-dependent-selects/
A working example: http://jsfiddle.net/20omnz2c/
$('#carmakes').on('change', function () {
var selected = $(this).val().toLowerCase();
if (selected != '0') {
$('#names').show();
$('#names option').hide(); //hide all options initially
$('#names option:eq(0)').show(); //show the first option
$('#names option.' + selected).show(); //show options with the right class
} else {
$('#names').hide();
$('#names option').hide();
}
});