I'm trying to get one select tag to populate based on the value of another select tag. The values for the populated select tag come from a JSON document.
The practical use here is for departing ferry terminals and what terminals they can reach.
Here is the code snippet I'm using
$(function(){
$("select#departingfrom").change(function(){
$.getJSON("/database.json", $(this).val(), function(ferries){
var options = '';
for (var key in ferries) {
options += '<option value=' + key + '>' + key + '</option>';
}
$("select#arrivingto").html(options);
});
});
});
Here's a small example of the JSON document
var ferries = {
"horseshoebay": {
"departurebay": {},
"langdale": {}
},
"departurebay": {
"horeshoebay": {}
},
"tsawwassen": {
"swartzbay": {},
"dukepoint": {}
},
"swartzbay": {
"tsawwassen": {},
"fulfordharbour": {}
},
"dukepoint": {
"tsawwassen": {}
},
"langdale": {
"horeshoebay": {}
},
"fulfordharbour": {
"swartzbay": {}
}
},
And then the HTML
<select id="departingfrom">
<option selected="selected"></option>
<option value="tsawwassen">Tsawwassen (Vancouver)</option>
<option value="swartzbay">Swartz Bay (Victoria)</option>
<option value="dukepoint">Duke Point (Nanaimo)</option>
<option value="departurebay">Departure Bay (Nanaimo)</option>
<option value="horseshoebay">Horseshoe Bay (North Vancouver)</option>
<option value="langdale">Langdale (Sunshine Coast)</option>
<option value="fulfordharbour">Fulford Harbour (Salt Spring Island)</option>
</select>
<select id="arrivingto">
<option selected="selected"></option>
</select>
I can't seem for the life of me to get the "function(ferries)" to run, so it makes me think that the .val is not working correctly. Let me know if you guys have any suggestions!