Forum Moderators: open

Message Too Old, No Replies

hiding text with select

hiding textbox using js

         

okutner

11:20 pm on Mar 7, 2006 (gmt 0)

10+ Year Member



Hi,
I'm kind of new at this, and would appreciate some help. I would like to have a "select" element with several options, and selecting one option ("other") will open a textbox for specification (and deselecting will hide it again). What I did was this:

<select id="lang" name="lang" size="1"
onchange="javascript: ShowOtherLang();">
<option value="0" selected>Language
<option value="en">English
<option value="sp">Spanish
<option value="ge">German
<option value="fr">French
<option value="other">Other
</select>
<div id='otherLang' style="display: none;"><input type="text" name="alt_lang" value="please specify"
</div>

and ShowOtherLang goes like this:

function ShowOtherLang()
{
var l = document.getElementById('lang');
var o = document.getElementById('otherLang');
if l == "other"
{
o.style.display = 'block';
}
}
I get an "error on page" when I try to change the select, and "other" won't show the textbox. What am I doing wrong?

whoisgregg

11:57 pm on Mar 7, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Welcome to WebmasterWorld, okutner!

What's happening is that your test for "l" is testing the wrong thing. If you alert(l), you'll see that it actually holds the entire SELECT object. You need to narrow down to the selected value.

This code should do the trick:

function ShowOtherLang() 
{
var l = document.getElementById('lang');
var o = document.getElementById('otherLang');
if (
l.value
 == "other")
{
o.style.display = 'block';
}
else
{
o.style.display = 'none';
}
}

Notice I also added an else that hides the div... just in case the user changes their mind and picks a standard language. Of course, your server side processing needs to also take that into consideration. A user might type in another language then go back and change their selection.

okutner

9:40 am on Mar 8, 2006 (gmt 0)

10+ Year Member



thanks - that works perfectly.