I have two fields select
, one I have states and another cities. I need to select in a select
a state, eg: São Paulo and in the other select
only bring the cities of são paulo.
I have two fields select
, one I have states and another cities. I need to select in a select
a state, eg: São Paulo and in the other select
only bring the cities of são paulo.
Starting from the principle that you will be working with JSON type data, but can be in any format ... you can get the onchange
event in select
states, and apply a filter in the city vector, searching for cities that have the selected state. Something like this:
var arrayDeCidades = [
{"nome":"Bauru", "estado":"sp" },
{"nome":"Ourinhos", "estado":"sp" },
{"nome":"Curitiba", "estado":"pr" }
];
document.getElementById("estados").onchange = function(){
var selCidades = document.getElementById("cidades");
selCidades.innerHTML = "";
var cidadesFiltradas = arrayDeCidades.filter(cidade =>{
return cidade.estado == this.value;
});
cidadesFiltradas.forEach(cidade =>{
var optionInc = document.createElement("OPTION");
optionInc.innerHTML = cidade.nome;
selCidades.appendChild(optionInc);
});
}
Estado:
<select id="estados">
<option>Selecione</option>
<option value="sp">São Paulo</option>
<option value="pr">Paraná</option>
</select>
Cidade:
<select id="cidades">
</select>
The way you will load the state combo and the data source of cities depends on your database (SQL, Ws that returns a JSON, I do not know).