PDA

View Full Version : Changing a property by selecting an <option>


soundboy
08-05-2004, 10:23 PM
Hi... I posted this in the CSS forum, but now it's more of a JS problem, so I'll transcribe it here.

I have a drop down list, made with <select> and <option>. Now, there's an option which reads "other", and what I want is for users to click on that option and have an additional text input box appear. I'm doing that by changing the "display" CSS property.

Now, the following code works:
function showExtra (divName) {
document.getElementById(divName).style.display="inline";
}

So I'll have an option in a drop-down menu with an "OnClick=showExtra(div1)" and have that div with an initial "style=display:none".


But now I want to have the div disappear if the option is unselected, so I add this, but it stops working:
function showExtra (divName, selectName) {
if (document.formName.selectName.value == 'other') {
document.getElementById (divName).style.display="inline";
} else {
document.getElementById(divName).style.display="none";
}
}

Where formName is the name of the form and selectName is the name of my drop-down menu, which contains the option 'other', and is the one I want to trigger the visibility of the 'div1' element.
I figure there's something wrong with my syntax, but can't quite put my finger on it.

dumpfi
08-05-2004, 10:45 PM
function showExtra (divName, selectName) {
var sel = document.forms['formName'][selectName];
document.getElementById(divName).style.display = (sel.options[sel.selectedIndex].value == 'other') ? 'inline' : 'none';
}
dumpfi

soundboy
08-06-2004, 10:42 PM
Hmm.. that didn't work either...

soundboy
08-07-2004, 02:53 PM
any more ideas? :D

dumpfi
08-07-2004, 03:27 PM
Sorry, but my solution DOES work. You must have made a mistake somewhere else.

Here is a working example of my code:
<html>
<head>
<script type='text/javascript'>
function showExtra (divName, selectName) {
var sel = document.forms['formName'][selectName];
document.getElementById(divName).style.display = (sel.options[sel.selectedIndex].value == 'other') ? 'inline' : 'none';
}
window.onload=hide;
function hide() {
document.getElementById('hoption').style.display = 'none';
}
</script>
</head>
<body>
<form name='formName'>
<select name='selectName' onChange='showExtra("hoption", "selectName")'>
<option value='first'>first</option>
<option value='second'>second</option>
<option value='other'>other</option>
</select>
<input type='text'id='hoption'>
</form>
</body>
</html>However, keep in mind that even if you hide the element, it's value is sent to the server on submit.

dumpfi

soundboy
08-07-2004, 06:43 PM
Whoops... sorry dumpfi, didn't mean to disrespect you or your advice. Most likely there's something else wrong with my form, I'll check it out when I get home.

Thanks a lot for your help!