Javascript: Get Select Dropdown Option Value on Button on Click

This article shows how to get selected value from dropdown box when a button is clicked.

Problem:

– There are multiple forms in a page.
– There is a dropdown select box in each form.
– The option value of the select box is website URL.
– There is a button type=button (not type=submit) in each form.
– User will select a value from the select box and click the button.
– I need to get the selected option value (which is website URL) and open the URL in new window.

Solution:

Here is my sample of multiple forms.


<form name="myForm_1" method="post" >				
	<select name='urls'>
		<option value="http://chapagain.com.np">Homepage</option>
		<option value="https://blog.chapagain.com.np">Blog</option>
		<option value="http://spiritualsatya.com">Spiritual</option>
	</select>	
	
	<button type="button" title="Download" onclick="openLink(document.forms['myForm_1'])">
		Download
	</button>
</form>
            				
<form name="myForm_2" method="post" >				
	<select name='urls'>
		<option value="http://facebook.com/mukesh.chapagain">Facebook</option>
		<option value="http://twitter.com/chapagain">Twitter</option>		
	</select>	
	
	<button type="button" title="Download" onclick="openLink(document.forms['myForm_2'])">
		Download
	</button>
</form>

Here is the Javascript.


<script type="text/javascript">
	function openLink(myForm)
	{					
		var selectedIndex = myForm.elements["urls"].selectedIndex;
		var url = myForm.elements["urls"].options[selectedIndex].value;
		window.open(url);
	}			
</script>

PS: This website is a great help for Javascript Coding – http://www.javascript-coder.com/javascript-form/javascript-form-submit.phtml

Thanks.