I haven’t done any of this for years (more than 10). I was never that good but now I’m totally lost on small things.
Below is my script, when it loads you see a select box with “Queensland” in it. based on the state you pick a second select box fills with cities. Problem is Queensland is the default and the second select box should already be filled with Queensland cities, but its not. Then if you open the select box you cant pick Queensland unless you pick another state first. Another words, I have totally stuffed up.
Could some show me where I have gone wrong, I was never good with functions
Script:
<!DOCTYPE html>
<html>
<body>
<select id="state" onchange="ChangeCityList()">
<option value="qld">Queensland</option>
<option value="nsw">NSW</option>
<option value="vic">Victoria</option>
<option value="sa">South Australia</option>
<option value="wa">Western Australia</option>
<option value="tas">Tasmania</option>
<option value="act">ACT</option>
<option value="nt">Northern territory</option>
</select>
<select id="city"></select>
<script>
var statescity = {};
statescity['qld'] = ['Gold Coast', 'Brisbane', 'McKay'];
statescity['nsw'] = ['Sydney', 'New Castle', 'Cambelltown', 'Penrith'];
statescity['vic'] = ['Melbourne', 'Ballarat', 'Geelong'];
statescity['sa'] = ['Adelaide', 'Coober Pedy', 'Murry Bridge', 'Nullabor'];
statescity['wa'] = ['Perth', 'Geraldton', 'Esperance'];
statescity['tas'] = ['Hobart', 'Launceston', 'Strahan'];
statescity['act'] = ['Canberra', 'Batemans Bay', 'Narooma'];
statescity['nt'] = ['Darwin', 'AliceSprings', 'Katherine'];
function ChangeCityList() {
var stateList = document.getElementById("state");
var cityList = document.getElementById("city");
var pickState = stateList.options[stateList.selectedIndex].value;
while (cityList.options.length) {
cityList.remove(0);
}
var state = statescity[pickState];
if (state) {
var i;
for (i = 0; i < state.length; i++) {
var states = new Option(state[i], i);
cityList.options.add(states);
}
}
}
</script>
</body>
</html>