Forum Moderators: open
<select size="1" name="HeaderFormat">
<option selected></option>
<option value="IBM_ASCII">IBM/ASCII</option>
<option value="UNISYS_EBCDIC">UNISYS/EBCDIC</option>
<option value="Other">Other</option>
</select>
and right below it, a text area:
<textarea rows="2" name="HeaderFormatOtherDetails" cols="72" tabindex="37"></textarea>
My question is, if someone selects the "Other" option in the dropdown, how can they be forced to fill out the text area?
Thanks,
Jim
There are really two parts to your question. First, how to make the textarea required, and second, to enforce the requirement.
The function checkOther below is attached to the onchange event of the select object. If the selected option is 'Other', the function (1) Sets the display style of the div containing the textbox to block from none, which makes the div visible and (2) sets a global variable flag fOther (set to false by default) to true.
The function doValidate enforces the rule. It checks the value of the fOther flag variable. If true and the length of the user input in HeaderFormatOtherDetails is less than or equal to one character long, it pops up an alert (you could substitute other code here) otherwise submits the form.
<script type="text/javascript">
<!--
//global flag variable used to see whether or not the
//user chose 'Other' from the HeaderFormat select object
var fOther=false
//this function shows/hides the textarea and set the flag
function checkOther(obj){
if(obj.options[obj.selectedIndex].value=='Other'){
document.getElementById('otherDiv').style.display='block'
fOther=true
}else{
document.getElementById('otherDiv').style.display='none'
fOther=false
}
}
//this function does very simple validation
function doValidate(){
if(fOther && document.getElementById('HeaderFormatOtherDetails').value.length<=1){
alert('Please enter your alternate header type')
}else{
document.forms[0].submit()
}
}
//-->
</script>
</head>
<body>
<form method="post" action="">
<select size="1" name="HeaderFormat" id="HeaderFormat" onchange="checkOther(this)">
<option value="" selected="selected">Choose header format</option>
<option value="IBM_ASCII">IBM/ASCII</option>
<option value="UNISYS_EBCDIC">UNISYS/EBCDIC</option>
<option value="Other">Other</option>
</select>
<div id="otherDiv" style="display:hidden;">
<textarea rows="2" name="HeaderFormatOtherDetails" id="HeaderFormatOtherDetails" cols="72" tabindex="37"></textarea>
</div>
<br />
<input type="button" onclick="doValidate()" value="Submit" />
</form>
</body>
Hope this helps,
ajkimoto