Combo box considering the previous choice

Asked

Viewed 51 times

-1

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

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

But keep mounting the link as below:

<div class="container">
  <input id="montadora" type="text" value="montadora"></input>
  <input id="modelo" type="text" value="modelo"></input>
  <input id="ano" type="text" value="ano"></input>
  <INPUT type="reset" name="b2" value="Limpar">
  <INPUT type="submit" name="b1" value="Pesquisar" onClick="location.href='http://www.rs1.com.br/'+document.getElementById('montadora').value+'/'+document.getElementById('modelo').value+'/'+document.getElementById('ano').value">
</div>

Remembering that instead of the user typing, he chooses the value in the dropdown.

  • None that simulate what I need, thanks more for the answer

1 answer

1


if I understand your doubt right, you want a form whose fields values select are created dynamically. If this is so, you can do it in the following way:

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 function escolha() will be called. In this function occurs a switch case which will evaluate which option was 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.

Obs.: If you want to dropdown using ul and li, or div, as a same menu, just adapt a little bit the code, making the loop for of switch case a <a href="#"></a> instead of option.

I hope I’ve helped.

Browser other questions tagged

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