Joseph Mate's Blog

Javascript to Redirect a Drop Down List (select)

Posted in Javascript by Joseph on March 5, 2010

You can redirect using an html select without having to place it in a form, or have the user press a button. The user only needs to change the value.

Check out the following code that you can copy and paste into an html file and take for a test drive:

<html>
	<head>
		<title>Drop Down List Redirect</title>
	</head>

	<body>
		<select onchange="top.location.href = 'http://www.google.com/search?q='
				+ this.options[ this.selectedIndex ].value" >
			<option value="">None</option>
			<option value="cute+dogs">Cute Dogs</option>
			<option value="lasers+beams">Laser Beams</option>
			<option value="kitty+cat">Kitty Cat</option>
		</select>
	</body>
</html>

Breaking down the javascript code into more understandable chunks gives:

// 'this' points to the select object after change the item in the drop down list.
var drop_down = this;

// drop_down.selectedIndex contains the position of the item that was selected from the drop down
var selected_index = drop_down.selectedIndex;

// drop_down.options contains all of html option elements inside the html select
// we need to go to .value to get the 'value="something"' written in the HTML
var selected_value = drop_down.options[ selected_index ].value;

// changing top.location.href redirects ( unless you only append #blah )
top.location.href = 'http://www.google.com/search?q=' + selected_value

I hope you guys find this helpful!

Cheers,
Joseph

About these ads

3 Responses

Subscribe to comments with RSS.

  1. Collin Cottrell said, on June 4, 2010 at 8:00 am

    Can you make the link open in a new window?

    THanks

  2. MyPC Solutions (@MyPC_Solutions) said, on July 13, 2012 at 7:21 pm

    I would like to have two drops down menus where I select options from the first drop down that auto-populates the items in the second drop down. When i select the second drop down option, it redirects me a to a specific url. Each option for the second drop down would have its own url.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: