| |
|
Example : Please Select any country from the country dropdown
In this tutorial we will learn how to change the options of a dropdown list dynamically using javascript.
You can add new options(Items) in a combo box using the javascript statement
form1.Cities.options[0] =new Option ('California' , '10');
The above javascript statement adds an item "California" with value "10" in a dropdown list named "Cities" at the first location of the dropdown list.
First we create the two dropdown lists within a form.
<form name="form1aa" method="post" action="" id="form1a" >
<select name="country" onchange=" fill_Cities (document.form1aa.country.selectedIndex); ">
<option value="India">India</option>
<option value="U.S.A">U.S.A</option>
<option value="Australia">Australia</option>
</select>
<select name="Cities">
</select>
</form>
In the above code , in the "onchange" event of the combo box, we have added a javascript statement
"fill_Cities (document.form1aa.country.selectedIndex); "
Here we are calling the javascript function fill_Cities
with the index of the item that has been selected by the user. The selectedIndex property of a combo box returns the position of the item selected by the user in a dropdown list.
Next we put the java script function
fill_Cities(document.form1aa.country.selectedIndex);
In the Head section
<head>
var i;
<script language="javascript">
var i;
function fill_Cities(i){
var form1 = document.getElementById("form1a");
document.form1aa.Cities.options.length=0;
switch(i)
{
case 0:
form1.Cities.options[0] =new Option('calcutta','calcutta');
form1.Cities.options[1] =new Option('Delhi','Delhi');
form1.Cities.options[2] =new Option('Bombay','Bombay');
break;
case 1:
form1.Cities.options[0] =new Option('Washington','Washington');
form1.Cities.options[1] =new Option('New York','New York');
form1.Cities.options[2] =new Option('California','California');
break;
case 2:
form1.Cities.options[0] =new Option('MelBourn','MelBourn');
form1.Cities.options[1] =new Option('Sidney','Sidney');
form1.Cities.options[2] =new Option('Perth','Perth');
}
}
</script>
</head>
Here the javascript code is self explanetory . The
statement
document.form1aa.Cities.options.length=0;
empties all the existing items in the dropdown list. Then different options are inserted in the "Cities" list depending upon the index of the item(passed as parameter "i" in the function through "onchange" event of the "country" drop down list).
Hope you have enjoyed the tutorial. Thank You.
Download Code
Back to Tutorial Index page
Your comments are most welcome admin@koderguru.com
|
|
|