Question

<html>
<head>
<title> Regioni </title>
</head>
<body>
<label>Selezione una regione</label>
<select name="regioni" id = "reg" name = "reg">
<option value="Abruzzo"> Abruzzo  </option>
<option value="Basilicata"> Basilicata </option><onClick="Basilicata(regione)">
<option value="Calabria"> Calabria </option>
<option value="Campania"> Campania </option>
<option value="Emilia-Romagna"> Emilia-Romagna </option>
<option value="Friuli-Venezia Giulia"> Friuli-Venezia Giulia </option>
<option value="Lazio" id ="lazio" onclick="Ch"> Lazio </option>
</select>
<br>
<label>Province</label> 
<select style="width:200" id="opt" name ="province">Province</select>
<script>                       
function Ch() 
{
var ddl = document.getElementById("reg");
var selectedValue = ddl.options[ddl.selectedIndex].value; 
if(selectedValue == "Lazio")
{  
var select = document.getElementById("opt");
select.options[select.options.length] = new Option('Roma', 'Viterbo'); 
}
else
{
alert('seleziona una provincia!');
}
} 
</script>
</body>
</html>

If I click lazio, I would like that in the second select box appear the provinces of the region Lazio.

You can do this? I tried but apparently does not work.

Was it helpful?

Solution 2

Just one addition to answer. To make it easier, and to avoid too many if/else blocks, you can make one object of arrays, and fill the content of select box, accordingly:

function Ch() {
  var opts = {
    'Lazio': ['Roma', 'Viterbo'], // add all arrays with provinzes here
    'Calabria': ['something1', 'something2']
  };
  var ddl = document.getElementById("reg");
  var selectedValue = ddl.options[ddl.selectedIndex].value;
  var select = document.getElementById("opt");
  select.innerHTML = '';
  for (i = 0; i < opts[selectedValue].length; i++) {
    var opt = document.createElement('option');
    opt.value = opts[selectedValue][i];
    opt.innerHTML = opts[selectedValue][i];
    select.appendChild(opt);
  }
}

OTHER TIPS

You need to use the onchange event on the select element;

<select name="regioni" id = "reg" name = "reg" onchange="ch();">
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top