JavaScript – Loading Select Box

 

Drop down box select box is used to select particular options from number of options available. Select box in JavaScript can be loaded dynamically and statically.
Select box options can change or add more options and remove option by JavaScript addOption and remove(length) function. Adding and removing options from select box is done without refreshing page in JavaScript.

Select box can be loaded dynamically, if it is more than one select box. Sometimes one select box options depend upon second select box and other select box accordingly to the previous value of select box. This dependent select box loaded on other select box value on onchange event, can be done in JavaScript.

Dependent select box is used in city and state option. State can have certain number of cities and load cities with come under a particular state.

In javascript, we have to store all cities data in javascript array. If state is selected, cities in this state should be loaded through an array.

If we change first option, second dependent option first remove from select box and load new value of array in options of select box.

Demo

<html>
<head>
<title>JavaScript Loading Select Box</title>
<script>
 function loadCity()
 {
   var jammu=new Array("Srinagar","Kathua","Doda","Kishtwar","Poonch","Rajouri");
   var punjab=new Array("Ludhiana","Amritsar","Bathinda","Firozpur");
   var tamilnadu=new Array("Chennai","Coimbatore","Cuddalore");

   var selectedBoxValue=document.frm.state.value;
   var i;
   var j;

   var cityLength=eval(selectedBoxValue).length;

   removeSelectboxOption();

   for(i=0;i<document.frm.state.options.length;i++)
   {
    if(selectedBoxValue==document.frm.state.options[i].value)
    {
      for(j=0;j<cityLength;j++)
      {
        document.frm.city.options[j]=new Option(eval(selectedBoxValue)[j],eval(selectedBoxValue)[j])
      }
    }
   }
 }

 function removeSelectboxOption()
 {
   var i;
   for(i=0;i<document.frm.city.options.length;i++)
   {
    document.frm.city.remove(i);
   }
 }
</script>
</head>

<body>
<form name="frm">
<select name="state" onChange="loadCity()">
<option value="jammu">Jammu</option>
<option value="punjab">punjab</option>
<option value="tamilnadu">Tamil Nadu</option>
</select>state

<select name="city">
</select> city
</form>
</body>
</html>

 

One Response to “JavaScript – Loading Select Box”

  1. Aditya Pandey says:

    Thanks for the code …