JS get value of selection from form select
Here’s a short script to use if you need to get the value of a selection list on the fly. It uses the onChange event that is attached to the select form element.
What I also wanted to achieve was to have a select list with one option as “other”. If other is chosen, a text field will display to let the user enter text.
<html><head>
<title>Select</title>
<style>#other {display:none;}</style>
<script tyle=”text/javaScript”>
function selectListValue()
{
var Beatle = beatles_list.beatles_member.options[beatles_list.beatles_member.options.selectedIndex].value;
if(Beatle == ‘other’)
{document.getElementById(‘other’).style.display=’block’;}
else{document.getElementById(‘other’).style.display=’none’;}
}
function TestDataCheck()
{
var Beatle = beatles_list.beatles_member.options[beatles_list.beatles_member.options.selectedIndex].value;;
var Other = beatles_list.other.value;
alert(Beatle+’ ‘+Other);
return false;
}
</script>
</head>
<body>
Choose a Beatle:<br />
<form method=”POST” name=”beatles_list” onSubmit=”return TestDataCheck()”>
<select size=”1″ name=”beatles_member” onChange=”selectListValue()”>
<option value=”john”>john</option>
<option value=”paul”>paul</option>
<option value=”george”>george</option>
<option value=”ringo”>ringo</option>
<option value=”other”>other</option>
</select>
<br /><br /><br />
<div id=”other”>Other:<br /><textarea name=”other”></textarea></div>
<input type=”submit” value=”submit” />
</form>
</body></html>