Get and Set the select box value

Author: Shivaprasad | Date: November 24, 2010

Learn how to Get/Set the value from the select box or combo box using JavaScript! In this article, we have two simple functions which will do that job. To set these options using jQuery read: Get and Set the select box options using jQuery

getSelectedvalue()” -> Will get the value of the combo box for the selected item.

setSelectBoxvalue()” -> Will set the value of the combo box with ‘optionText‘(Variable used in the tutorial see the “setSelectBoxvalue()” function).

This script is very straight forward/Simple. If you have any doubts please post it here. I will answers.

HTML:

<form name="dummyForm">
	<select name="selectBox" onchange="getSelectedvalue()">
		<option value="option 1">option 1</option>
		<option value="option 2">option 2</option>
		<option value="option 3">option 3</option>
		<option value="option 4">option 4</option>
		<option value="option 5">option 5</option>
		<option value="option 6">option 6</option>
		<option value="option 7">option 7</option>
		<option value="option 8">option 8</option>
	</select>
</form>

<a href="javascript:setSelectBoxvalue()">Click me</a>

Javascript:

function getSelectedvalue()
{
	var getSelectedIndex = document.dummyForm.selectBox.selectedIndex;
	var getSelectedOptionText = document.dummyForm.selectBox[getSelectedIndex].text;
	alert(getSelectedOptionText);
}

function setSelectBoxvalue()
{
	var len = document.dummyForm.selectBox.length;
	//alert(len);
	var optionText= 'option 1';
	for(var i=0; i<=len; i++){
		if( (document.dummyForm.selectBox[i].value) == optionText){
			alert(document.dummyForm.selectBox[i].text);
			document.dummyForm.selectBox.selectedIndex = i;
		}
	}

}