Search This Blog

Nov 8, 2012

Dynamically populate drop-down that is part of form array

I will show you the HTML code, this code consist of two dropdownlist / combo box (two <select> element) with the second <select> element disabled and will be enabled if we choose something from the first <select> element. Here the HTML code (dnmddl.htm):


<!doctype html public "-//w3c//dtd html 3.2//en">
<title>(Type a title for your page here)</title>
<script language="javascript" src="list.js"></script>

<body bgcolor="#ffffff" text="#000000" link="#0000ff" vlink="#800080" alink="#ff0000" onLoad="fillCategory();">

<FORM name="drop_list" action="yourpage.php" method="POST" >
<SELECT  NAME="Category" onChange="SelectSubCat();" >
<Option value="">Category</option>
<SELECT id="SubCat" NAME="SubCat">
<Option value="">SubCat</option>



Don’t be afraid, eventhough the Javascript code look a bit large but what is done by this code only initialize the array with specified value and fill it to the second dropdownlist element (slc_target). This is the Javascript code (dynamicddl.js):


function fillCategory(){
 // this function is used to fill the category list on load
addOption(document.drop_list.Category, "Fruits", "Fruits", "");
addOption(document.drop_list.Category, "Games", "Games", "");
addOption(document.drop_list.Category, "Scripts", "Scripts", "");

function SelectSubCat(){
// ON selection of category this function will work

addOption(document.drop_list.SubCat, "", "SubCat", "");

if(document.drop_list.Category.value == 'Fruits'){
addOption(document.drop_list.SubCat,"Mango", "Mango");
addOption(document.drop_list.SubCat,"Banana", "Banana");
addOption(document.drop_list.SubCat,"Orange", "Orange");
if(document.drop_list.Category.value == 'Games'){
addOption(document.drop_list.SubCat,"Cricket", "Cricket");
addOption(document.drop_list.SubCat,"Football", "Football");
addOption(document.drop_list.SubCat,"Polo", "Polo", "");
if(document.drop_list.Category.value == 'Scripts'){
addOption(document.drop_list.SubCat,"PHP", "PHP");
addOption(document.drop_list.SubCat,"ASP", "ASP");
addOption(document.drop_list.SubCat,"Perl", "Perl");


function removeAllOptions(selectbox)
    var i;

function addOption(selectbox, value, text )
    var optn = document.createElement("OPTION");
    optn.text = text;
    optn.value = value;


No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...