Archive

Archive for December, 2006

Toggle the Fields

December 7, 2006 1 comment

While designing the web pages, sometimes you need to show the particular input field or labels or other page element, and show them on some event like click of a button, change the option from combobox ect.

One idea is make the field to be toggled, invisible by default and make it visible on that particular event. Here I am presenting some sample code, to achieve this :

<script language=”javascript” type=”text/javascript”>

function toggle_field()
{
var changed = document.getElementById(‘enter_card’);
var card1 = document.getElementById(‘hide_field1’);
var card2 = document.getElementById(‘hide_field2’);
if(changed.options[changed.options.selectedIndex].value)
{
card1.style.display = ‘block’;
card2.style.display = ‘block’;

}
else
{
card1.style.display = ‘none’;
card2.style.display = ‘none’;

}
}

</script>

<html><body>

<table>

<tr>

<td >Select option to show hidden elements:</td>
<td>
<select id=”enter_card” name=”card_type” onchange=”toggle_field()”>
<option value=””>Choose….</option>
<option value=”Option1″>Option1</option>
<option value=”Option2″>Option2</option>
<option value=”Option3″>Option3</option>
</select>
</td>
</tr>
<tr>
<td><div id=”hide_field1″ style=”display: none;”>Card Number:</div></td>
<td><div id=”hide_field2″ style=”display: none;”><input type=”text” name =”card_number” value=”” size=”40″></div></td>
</tr>

</body></html>

The label “card number” and the input field “card_number” will be invisible by default. When somebody selects any option from the dropdown box, the function toggle_field() makes the invisible fields to visible and vice-versa. This code will help in toggling the page elements. Cheers…

Categories: Java Script