I'm trying to set up this associative array, in case the combobox is the state of São Paulo, you have to show 5 cities in São Paulo, if it's Rio de Janeiro, it 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);
}
Perfectly returning states in the combobox. What I want now is that when I select the state show the cities in the other combobox, when Rio shows the cities of Rio and when Select Sao Paulo shows the cities of São Paulo. So I did this, but it does not return anything
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 select variable, if it exists it enters the if, but the variable selectedText that I did to receive the value of the combobox of the state it returns empty. Before I had left inside the for, there I repeated the empty field 5 times, I took from inside for it it repeats once but still yes empty.
Thanks in advance for any help.