2
I’m trying to set up this associative array, in the case of the combobox is the state of São Paulo, it has to show 5 cities of São Paulo, if it is Rio de Janeiro, shows the 5 cities of Rio de Janeiro.
HTML
<select id = "estados">
<option></option>
</select>
<select id = "cidade">
<option></option>
</select>
Javascript
var select = document.getElementById("estados");
var cidade = document.getElementById("cidade");
var options = ["São Paulo", "Rio de Janeiro"];
var cidade1 = ["São Paulo", "Itápolis", "Araraquara", "Ribeirão Preto", "Jacareí"];
var cidade2 = ["Rio de Janeiro", "Niteroi", "Petropolis", "Belford Roxo", "Nova Iguaçu"];
In the following code it brings all states, so far so good.
for(var i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
//console.log(el)
select.appendChild(el);
}
Returning perfectly the states in the combobox. What I want now is that when I select the state show the cities in the other combobox, when Rio show the cities of Rio and when Select São Paulo show the cities of São Paulo. So I did it, but nothing comes back
Javascript
if(select){
var t = document.getElementById("estados");
var selectedText = t.options[t.selectedIndex].text;
if(selectedText == 'São Paulo'){
for(var j = 0; j < cidade1.length; j++) {
var opt = cidade1[j];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
cidade.appendChild(el);
}
}
if(selectedText == 'Rio de Janeiro'){
for(var j = 0; j < cidade2.length; j++) {
var opt = cidade2[j];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
cidade.appendChild(el);
}
}
}
I took the variable select, if it exists enters if, but the variable selectedText I did to receive the value of the state’s combobox it returns empty. Before I had left inside the outdoors, then repeated the empty field 5 times, removed inside the for it repeats once but still empty.
From now on I appreciate any help.
Hit man, vlw !
– Alison Paulo