• en
  • sv
code2

Javascript Snippet: Go to Site Selected in Drop-down Menu

Once in a while I need users to be able to select an option in a drop-down menu and have the option load a URL directly. This isn’t possible with just HTML alone but with a quick little javascript function, this is easily achieved.

The Javascript

It isn’t really that hard of a javascript snippet. First we set up a variable (named URL here) which grabs the value of our selected url list based on the class applied to the list. Finally it loads this URL into the address bar and submits it. I have bolded the two bits of the snippet that needs to be replaced with the name of the form in the HTML code.

<script language="javascript">
	function gotosite() {
		var URL = document.event_type_selector.url_list.options[document.event_type_selector.url_list.selectedIndex].value; window.location.href = URL;
	}
</script>

The HTML

This is really just a standard drop-down box in a form element that calls the javascript function. The only thing to pay attention to is the name given to the form which is used in the javascript selector above (bolded).

<form name="event_type_selector" method="post" action="#">
	<select name="url_list" class="event-type-selector-dropdown" onchange="gotosite()">
		<option value="" selected="selected" disabled="disabled">Please select...</option>
		<option value="?id=1">Option 1</option>
		<option value="?id=2">Option 2</option>
		<option value="?id=3">Option 3</option>
	</select>
</form>

Using these two snippets together will render you a nice HTML drop-down box that upon selection takes you to a new URL very useful when filtering results in a sorting list for example.

About the author

Erik Bernskiold is the owner of XLD Studios and software education company Bernskiold Media. He is a WordPress lover, speaker and self-proclaimed tech geek, located in Gothenburg, Sweden.