Validation of two selects

Asked

Viewed 513 times

1

I have two camps select, I have states and other cities. I need to select in a select one state, ex: São Paulo and the other select bring only the cities of Sao Paulo.

  • You already have the database of states and cities ?

  • and what did you try to do? show your code so we can help you.

  • There are several questions here on stackoverflow PT addressing this topic... you have some mechanism of back-end? Where do you save the values of cities and states? Do you have any table with the relations? Which database?

1 answer

3


Starting from the principle that you will be working with JSON type data, but it can be in any format... you can get the event onchange in the select of states, and implement 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 origin of the city data depends on your database (SQL, Ws that returns a JSON, I do not know).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.