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.


function getSelectLabel(obj)
return obj.options[obj.selectedIndex].text;


<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>


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




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

No comments: