sexta-feira, 13 de fevereiro de 2015

Combobox Dinâmica com JavaScript usando arrays


Primeiro crie o seguinte arquivo HTML chamado selectDinamico.html

<html> 
  <head> 
    <meta http-equiv="content-type" content="text/xhtml; charset=utf-8" /> 
    <title>Combobox dinâmico</title> 
<script language="JavaScript" src="comboDinamico.js"></script>
</head>
<body>
  <h1>Select dinâmico em JavaScript</h1>
<label for="estado">Estado</label>
     <select id="continent" onchange="comboDinamica(this);">
        <option value="empty">Selecione um Estado</option>
        <option value="SaoPaulo">São Paulo</option>
<option value="RioGrandedoSul">Rio Grande do Sul</option>
<option value="SantaCatarina">Santa Catarina</option>
     </select>
  <br/><br/>
  <label>Cidade</label>
  <select id="atributo1">
    <option value="0">Cidade</option>
  </select>
</body>
</html>


Em seguida crie este arquivo Javascript com o seguinte nome: comboDinamico.js

var countryLists = new Array(5) 

 countryLists["empty"] = ["Selecione um Estado"]; 
 countryLists["RioGrandedoSul"] = ["Alvorada", "Porto Alegre", "Bom Jesus", "Capivari do Sul"]; 
 countryLists["SaoPaulo"] = ["Artur Nogueira", "Balbinos", "BARRETOS", "São Paulo", "GUARULHOS"]; 
 countryLists["SantaCatarina"] = ["Florianópolis", "Biguaçu", "São José", "Palhoça", "Lages", "Tijucas", "Balneário Camboriú"]; 

 function comboDinamica(selectObj) { 
 // get the index of the selected option 
 var idx = selectObj.selectedIndex; 
 // get the value of the selected option 
 var which = selectObj.options[idx].value; 
 // use the selected option value to retrieve the list of items from the countryLists array 
 cList = countryLists[which]; 
 // get the country select element via its known id 
 var cSelect = document.getElementById("atributo1"); 
 // remove the current options from the country select 
 var len=cSelect.options.length; 
 while (cSelect.options.length > 0) { 
 cSelect.remove(0); 
 } 
 var newOption; 
 // create new options 
 for (var i=0; i<cList.length; i++) { 
 newOption = document.createElement("option"); 
 newOption.value = cList[i];  // assumes option string and value are the same 
 newOption.text=cList[i]; 
 // add the new option 
 try { 
 cSelect.add(newOption);  // this will fail in DOM browsers but is needed for IE 
 } 
 catch (e) { 
 cSelect.appendChild(newOption); 
 } 
 } 
 } 


Entendendo o que está acontecendo: primeiramente nós criamos dois selects. Um com as options de Estados, e o outro sem options, pois serão apresentadas dinamicamente quando determinada option do primeiro select forem selecionadas. O primeiro select tem ação onChange no método comboDinamica(this);  que se encontra no arquivo javascript. Este método é responsável por fazer a associação das opções entre as combobox. 


About the Author

Unknown

Author & Editor

Has laoreet percipitur ad. Vide interesset in mei, no his legimus verterem. Et nostrum imperdiet appellantur usu, mnesarchum referrentur id vim.

3 comentários:

 
Academy Programming © 2015 - Designed by Templateism.com