I use the the code below from "Use jQuery to change a second select list based on the first select list option" to change a second select list based on the first select list option. It works very well. But how can I assigning the "selected" attribute to the option on this code for both selects.
JavaScript:
$(document).ready(function () {
"use strict";
var selectData, $states;
function updateSelects() {
var cities = $.map(selectData[this.value], function (city) {
return $("<option />").text(city);
});
$("#city_names").empty().append(cities);
}
$.getJSON("updateSelect.json", function (data) {
var state;
selectData = data;
$states = $("#us_states").on("change", updateSelects);
for (state in selectData) {
$("<option />").text(state).appendTo($states);
}
$states.change();
});
});
HTML:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
</head>
<body>
<select id="us_states"></select>
<select id="city_names"></select>
<script type="text/javascript" src="updateSelect.js"></script>
</body>
</html>
JSON:
{
"NE": [
"Smallville",
"Bigville"
],
"CA": [
"Sunnyvale",
"Druryburg",
"Vickslake"
],
"MI": [
"Lakeside",
"Fireside",
"Chatsville"
]
}