JavaScript Dynamic Combo Box


 

JavaScript Dynamic Combo Box

Here we are going to create dynamic combo box.

Here we are going to create dynamic combo box.

JavaScript Dynamic Combo Box

Here we are going to create dynamic combo box. For this, we have created two combo boxes where combo1 represents countries and combo2 represents the cities. The values of the combo boxes are stored in respective arrays. As the user selects a country from the first combo box, the cities of that country, get populated into the second combo.

Here is the code:

<html>
<
h2>ComboBox</h2>
<
script language="javascript">
var arr = new Array();
arr[0] = new Array("-select-");
arr[1] = new Array("Maharashtra","Karnataka","Andhra Pradesh","Tamil Nadu");
arr[2] = new Array("Carinthia"," Styria");
arr[3] = new Array("Florida","New York","Maryland");
arr[4] = new Array("Queensland","Victoria","Tasmania","New South Wales");

function change(combo1){
var comboValue = combo1.value;
document.forms["form"].elements["combo2"].options.length=0;
for (var i=0;i<arr[comboValue].length;i++){
var option = document.createElement("option");
option.setAttribute('value',i+1);
option.innerHTML = arr[comboValue][i];
document.forms["form"].elements["combo2"].appendChild(option);
}
}
</script>
<
form name="form" method="post"><select name="combo1" onchange="change(this);">
<
option value="0">-Select-</option>
<
option value="1">India</option>
<
option value="2">Austria</option>
<
option value="3">USA</option>
<
option value="4">Australia</option>
</
option>
</
select><br />
<
select name="combo2">
</
select>
</
form>
</
html>

Output:

On selecting the value from the first combo, related values will get displayed in second combo:

Ads