Dynamically filling ComboBoxes

If you are developing a professional site for a company you would invariably come across a situation where you are expected to do the above. Remember that the power of this script becomes evident when you use Javascript along with some other dynamic language such as JSP or ASP. You could probably fill the arrays used in this script with some data fetched from a database relating to the particular user. When he selects an entry in the first dropdown menu, he is immediately presented with his relevant data in the second menu, instead of making another request to the server to fetch more data. These types of scripts are very useful when you have to allow a user select some thing from a general level to a more specific level. I mean each successive dropdown menu would be more and more specific choice. Read on to understand the entire thing.

<SCRIPT LANGUAGE = "JavaScript">
<!--

var tennisplayers= new Array("Safin", "Andre Agassi", "Pete Sampras", "Anna Kournikova", "Martina Hingis");
var cricketplayers = new Array("Sachin Tendulkar", "Steve Waugh", "Brian Lara", "Sir Don Bradman");

function set_player() {

 var select_sport = document.myform.sport;
var select_player = document.myform.player;
var selected_sport = select_sport.options[select_sport.selectedIndex].value;

select_player.options.length=0;
if (selected_sport == "tennis"){

   for(var i=0; i<tennisplayers.length; i++)  
   select_player.options[select_player.options.length] = new Option(tennisplayers[i]);
 }
if (selected_sport == "cricket"){

   for(var i=0; i<cricketplayers.length; i++)
     select_player.options[select_player.options.length] = new Option(cricketplayers[i]);
 }
}
-->
</SCRIPT>

<BODY>
<FORM NAME="myform" METHOD="POST">

Sport
<SELECT NAME="sport" onChange="set_player()">
<OPTION VALUE="tennis">-------
<OPTION VALUE="tennis">Tennis
<OPTION VALUE="cricket">Cricket
</SELECT>

Player
<SELECT NAME="player">
<OPTION>------
</SELECT>

</FORM>
</BODY>

You might also like...

Comments

Kiran Pai

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“An expert is a man who has made all the mistakes that can be made in a very narrow field” - Niels Bohr