Thursday, April 30, 2009

Javascript example for selectively displaying particular div based on drop-down selection

display property of style for any div tag can be set as "block" to display the div content, or it can be set as "none" to hide the contents of div tag.

Here I will explain how to use this display property to hide or show a div tag based on the value selected in a drop down list.

Consider below HTML form having two drop-down lists. One (appointment_for) is having two options myself and others.

The another drop-down list (appointment_for_others[]) is placed inside a div tag which is hidden by default using style "display:none".

<form name="frmadd">
<select name="appointment_for" id="appointment_for" onChange="showHideOthers();">

<option value="myself" selected>Myself</option>
<option value="others">Somebody Else</option>
<div id="others" style="display:none" >
<select name="appointment_for_others[]" id="appointment_for_others" multiple size="3">
<option value="" selected>Select</option>
<option value="Name1" >Name1</option>
<option value="Name2" >Name2</option>


Here our intention is to show the second drop-down list on selecting other in the first drop-down list.

To achieve this we can call a javascript function during onChange event of first drop-down list to unhide the second drop-down list on selecting other in the first one.

Find the below sample javascript function used for this purpose.

<script language="javascript">
function showHideOthers()
if (document.frmadd.appointment_for.selectedIndex==0) //Hide others drop-down list if myself is selected
else //show drop-down list of others

You can visually see it here. If you select 'Others' in the below drop-down list you can see another drop-down list here.

More Articles...

No comments:

Search This Blog