Dylan Byrne Dylan Byrne - 9 months ago 31
HTML Question

I'm trying to create a dynamic menu on a HTML web page using JavaScript, but keep having trouble

Okay so here is my HTML code

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<script type="text/javascript" src="Cities.js">

<select id="Countries" name="countries" onchange="populate('Countries','Cities')">
<option value="">Country</option>
<option value="Ireland">Ireland</option>
<option value="Romania">Romania</option>
<option value="England">England</option>
<option value="Spain">Spain</option>
<option value="Germany">Germany</option>

<select id="Cities" name="cities">
<option value="">Cities</option>



Okay, so all seems good here so far and here is my JavaScript code

//Populates Countries and Cities select form elements

function populate(s1,s2)


var s1 = document.getElementById(s1);//s1==Countries

var s2 = document.getElementById(s2);//s2==Cities


* if s1==Ireland print Dublin
var optionArray = ["|", "dublin|Dublin"];
* If s1==Romania print Bucharest
else if (s1.value=="Romania"){
var optionArray=["|", "bucharest|Bucharest"];

* if s1==England print Liverpool
else if (s1.value=="England"){
var optionArray=["|", "liverpool"|"Liverpool"];

* if s1==Spain print Madrid
else if (s1.value=="Spain") {
var optionArray=["|", "madrid"|"Madrid"];

* if s1==Germany print Munich
else if (s1.value=="Germany"){
var optionArray=["|","munich"|"Munich"];

for(var option in optionArray){
var pair = optionArray[option].split("|");
var newOption = document.createElement("option");
newOption.value = pair[0];


As you can see what I'm trying to do is create if and if else statements so that if a certain select element from the html file is selected that it will print out a city from that country.

Now the weird part is that it works perfectly for Ireland and Romania and when they are selected I have the option to select Dublin or Bucharest from the other drop down menu, but it does not work for any of the other 3 countries?

Now seeing as it works for the first two select elements this makes me think that there is a problem either in my for loop or my HTML code but I'm not entirely sure. It might even just be a small problem staring me in the face that I just can't see.

Any help would be greatly appreciated, thank you.


Like Andreas mentioned the problem lies with the quotes in optionsArray assigment in the first two its correct:

var optionArray = ["|", "dublin|Dublin"]

After that its like this:

var optionArray=["|", "liverpool"|"Liverpool"]

See the extra quotes

Here is the corrected example i made for you.