Combo box considering the previous choice

0

Good morning, I have a question about how to do a combo box in the previous choice of input, for example:

If you choose SP I will have three options in the list Sorocaba, Boituva, Tatuí

More than still continue to mount the link as in the link below:

JsFiddle: link

More remembering that instead of the user typing it choose the value in the dropdown.

I do not know if you understand my doubt! Thanks in advance for your help!

    
asked by anonymous 29.08.2015 / 16:30

1 answer

1

If you understand your question correctly, you want a form whose values from the select fields are created dynamically. If so, you can do it as follows:

var arr_cidades = {
  sp: ["Sorocaba", "Boituva", "Tatuí"],
  rj: ["Uma cidade do Rio", "Outra cidade"]
}

function escolha() {
  var estado = document.querySelector("#estado");
  var cidade = document.querySelector("#cidade");

  cidade.disabled = false;

  cidade.innerHTML = "";

  switch (estado.value) {
    case "sp":
      for (i in arr_cidades.sp) {
        cidade.innerHTML += "<option>" + arr_cidades.sp[i] + "</option>"
      };
      break;
    case "rj":
      for (i in arr_cidades.rj) {
        cidade.innerHTML += "<option>" + arr_cidades.rj[i] + "</option>"
      };
      break;
    default:
      cidade.innerHTML += "<option>- Selecione uma cidade -</option>";
      cidade.disabled = true;
  }
}
<span>Estado</span>
<br>
<select id='estado' onchange="escolha()">
  <option value=''>- Selecione um Estado -</option>
  <option value='sp'>SP</option>
  <option value='rj'>RJ</option>
</select>
<br>
<br>
<span>Cidade</span>
<br>
<select id='cidade' disabled="true">
  <option value=''>- Selecione uma Cidade -</option>
</select>

As you can see, I created an array with the cities, and when the user selects a particular option the escolha() function will be called. In this function there is a switch case that evaluates the option chosen in the previous field and according to this will select the cities in the array, after that creates the options in the next field.

If you want to do a dropdown, using ul and li , or div , as a menu itself, just adapt a little bit.

the code, causing the loop for of the switch case to be generated a <a href="#"></a> instead of option .

I hope I have helped.

    
02.09.2015 / 18:33