Tuesday, May 12, 2009

Javascript code for changing list box (select tag) value based on change in another listbox

Javascript can be effectively used for dynamically changing value in one drop down list (i-e select/option tag) when a value in another related drop-down list is changed.

Assume that a webpage is having list of names in one drop-down list and the corresponding ages in another drop-down list as below.

If you select "Name1" in the first drop-down list, corresponding value "Age1" will be selected in the second list box.

And, also if you select "Age2" in the second list then "Name2" will be selected automatically.

It is done using javascript function.

The HTML code will look like below for showing these two drop-down lists.

<form name="frmselect" id="frmselect" action="" method="post">
<select name="name" id="name" onChange="javascript:return setage();">
<option value="" selected>Select Name</option>
<option value="1">Name1</option>
<option value="2">Name2</option>
<select name="age" id="age" onChange="javascript:return setname();">
<option value="" selected>Select Age</option>
<option value="a">Age1</option>
<option value="b">Age2</option>

onChange event of the Name drop-down list calling javascript function setage()for changing value in Age drop-down list.

Find below the javascript code which needs to be included within Head section of HTML file.

<script language="javascript" type="text/javascript">
/*function for changing age when changing the name
function setage()
var index_name=document.frmselect.name.selectedIndex;

/*function for changing name when changing the age.
function setname()
var index_age=document.frmselect.age.selectedIndex;


The setage function gets the selectedIndex value of Name list and assign this value as selected Index of age list.

setname also behaves similarly for changing name when age is changed.

More Articles...

No comments:

Search This Blog