How to create a select menu related to another select menu
For example when you select Iraq from the first select menu, the second select menu will display only Iraqi cities, and if you select Jordan in the first select menu, only Jordanian cities will appear in the second select menu. For me this is a success in two areas, first writing the jQuery program and second using the JSfiddle IDE for the first time.
by Akram kamal
HTML
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<select id="country">
<option>--Select--</option>
<option>Iraq</option>
<option>Jordan</option>
</select>
<br/>
<br/>
<label>Select City:</label>
<br/>
<br/>
<select id="city">
<!--Dependent Select option field-->
</select>
CSS
h2 {
text-align: center;
}
label {
color: #464646;
text-shadow: 0 1px 0 #fff;
font-size: 14px;
font-weight: bold;
}
select#country, #city {
width:70%;
height:30px;
font-size:14px;
font-family:Aharoni;
}
select#Iraq, select#Jordan {
display:none;
width:100%;
height:30px;
font-size:16px;
font-family:script;
}
JavaScript
$(document).ready(function () {
//Initializing arrays with city names
var Iraq = [{
display: "Baghdad",
value: "Baghdad"
}, {
display: "Ninava",
value: "Ninava-Mosul"
}, {
display: "Basrah",
value: "Albasrah"
}, {
display: "Anbar",
value: "RamadiFaluja"
}, {
display: "Dyala",
value: "Dyala-Baquba"
}, ];
var Jordan = [{
display: "Aqaba",
value: "JordanAqaba"
}, {
display: "Amman",
value: "JordanAmman"
}, {
display: "Zarqaa",
value: "JordanZarqaa"
}, {
display: "Jarash",
value: "JordanJarash"
}, {
display: "Irbid ",
value: "JordanIrbid"
}];
$("select").selectmenu();
//Function executes on selectmenuchange of first select option field
$("#country").on( "selectmenuchange", function() {
var select = $("#country option:selected").val();
switch (select) {
case "Iraq":
city(Iraq);
break;
case "Jordan":
city(Jordan);
break;
default:
city([])
break;
}
});
//Function To List out Cities in Second Select tags
function city(arr) {
$("#city").selectmenu("destroy")
$("#city").empty(); //To reset cities
if (arr.length) $("#city").append("<option>--Select--</option>");
$(arr).each(function (i) { //to list cities
$("#city").append("<option value=\"" + arr[i].value + "\">" + arr[i].display + "</option>")
});
$("#city").selectmenu()
}
});