Thursday 9 October 2008

Javascript Function That Returns A Select Label

This is a little example function to return the label of an html select form element, which is simple but not as immediately obvious as getting the value.

<html>

<head>
<script>
function getSelectLabel(obj)
{
return obj.options[obj.selectedIndex].text;
}
</script>
</head>

<body>

<h1>Get Select Label</h1>

<form name="testForm">

<select name="testSelect">
<option value="r">Red</option>
<option value="g">Green</option>
<option value="b">Blue</option>
</select>

<br/>
<br/>

<input type="button" onclick="alert(getSelectLabel(document.testForm.testSelect));" value="Get Label"/>
<input type="button" onclick="alert(document.testForm.testSelect.value);" value="Get Value"/>

</form>

</body>

</html>

I've also added a second button to display the value for reference.
Done...

No comments: