logo

select-one controls value and display text JavaScript

JavaScript: The Definitive Guide

Overview: This code snippet shows how to get a a select-one value or display text

<html><head><title>List Box Selection</title>

<script language="javascript1.1">

function getSelectedText(lbxListBox)

{ 

var stRetVal; 

var iIndex; 

stRetVal="";

/*Gets the Selected Item's index and used the

options object to get the text value*/



	stRetVal=lbxListBox.options[lbxListBox.selectedIndex].text; 

return(stRetVal); 

} 

</script>



<body>



<h3>List Box Items</h3>

<form name="frmMain">

<select name="lbxItems">

<option value="1">Hello World

<option value="2">Hello Salt Lake City

<option value="3">Hello Ogden

</select>

</form>



<h3>Javascript Results</h3>

<pre>

Select Item Value<input type="textbox" name="txtValueResults" size="30"><input type="button" value="Press Me" onClick="txtValueResults.value=frmMain.lbxItems.value;">

Select Item Text<input type="textbox" name="txtTextResults" size="30"><input type="button" value="Press Me" onClick="txtTextResults.value=getSelectedText(frmMain.lbxItems);">

</pre>

</body>

</html>
s