Dynamic Text Boxes

Question: My task is to define a drop down menu with a list of values such as name, age, others, etc. When the user selects others, a text field should appear for the user to define what others means. How can I use Javascript to hide the text field except when others is selected?

Answer: The following will do what you want in Internet Explorer, Opera, and Netscape 6+. This code does not work with Netscape 4 and the text box will always be visible in that browser.


The code to place the fields in the form is as follows (note that the onchange code shown in bold should be all on the same line):

 <select name="values" size="1"
onchange="toggleOther( document.myform.values.options[ document.myform.values.selectedIndex ].value );">
<option value=" " selected="selected"> </option>
<option value="name">Name</option>
<option value="age">Age</option>
<option value="oth">Other</option>
<input type="text" name="other" value="" size="25" maxlength="40" style="visibility:hidden" />

The style parameter on the text field tells the browser not to display the field when the page is first displayed. The onchange parameter on the selection field will toggle the visibility of the text field by calling the following javascript:

 function toggleOther(chosen) {
if (chosen == 'oth') {
  document.myform.other.style.visibility = 'visible';
} else {
  document.myform.other.style.visibility = 'hidden';
  document.myform.other.value = '';

This code will make your text field visible when Other is selected in the drop down list and will hide it again and remove any assigned value when you change to a different selection.


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow