Click here to Skip to main content
Click here to Skip to main content

Using JavaScript to handle drop-down list selections

By , 25 Jul 2009
 

Introduction

We've all seen sites that feature drop down lists that automatically take you to your selection without you needing to make the cumbersome and lengthy step of hitting a "Go" button. If you've ever wondered how they do this then as you probably expected it's very simple.   

What on Earth am I talking about?

Picture a drop down list as follows:

Screenshot - dropdown.png

We often see a button next to the list that the user should press in order to actually activate there selection:

Screenshot - dropdown2.png

The user selects the value from the dropdown, hits Go, and the choice is made. By using javascript we can have the list notify us when a change is made, and we can essentially hit that Go button for the user. Not only do we save the use all the hassle of clicking on a button, we also get a handy reduction in the amount of screen real estate used.

How do we do it?

A typical dropdown list is instantiated using the following:

<select name=select1>
<option>Value 1</option>
<option>Value 2</option>
<option>Value 3</option>
</select>

(Give or take some attributes). What we do is add an attribute that instructs the page to call our handler for when the list selection is changed.

<select name=select1 onchange='OnChange(this.form.select1);'>

Our handler will look up the value that has just been selected, and navigate to an appropriate URL. An example of this is shown below:

<SCRIPT LANGUAGE="javascript">
<!--
function OnChange(dropdown)
{
    var myindex  = dropdown.selectedIndex
    var SelValue = dropdown.options[myindex].value
    var baseURL  = <Some value based on SelValue>
    top.location.href = baseURL;
    
    return true;
}
//-->
</SCRIPT>

What if the user isn't using JavaScript?

We use the <noscript> tag to help us. We provide a Go button for the list, but only show it if JavaScript is not present:  

<select name=select1>
<option>Value 1</option>
<option>Value 2</option>
<option>Value 3</option>
</select><noscript><INPUT type="submit" value="Go" name=submit1></noscript>

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Chris Maunder
Founder CodeProject
Canada Canada
Member
Chris is the Co-founder, Administrator, Architect, Chief Editor and Shameless Hack who wrote and runs The Code Project. He's been programming since 1988 while pretending to be, in various guises, an astrophysicist, mathematician, physicist, hydrologist, geomorphologist, defence intelligence researcher and then, when all that got a bit rough on the nerves, a web developer. He is a Microsoft Visual C++ MVP both globally and for Canada locally.
 
His programming experience includes C/C++, C#, SQL, MFC, ASP, ASP.NET, and far, far too much FORTRAN. He has worked on PocketPCs, AIX mainframes, Sun workstations, and a CRAY YMP C90 behemoth but finds notebooks take up less desk space.
 
He dodges, he weaves, and he never gets enough sleep. He is kind to small animals.
 
Chris was born and bred in Australia but splits his time between Toronto and Melbourne, depending on the weather. For relaxation he is into road cycling, snowboarding, rock climbing, and storm chasing.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Questioncodes downloadsmembersiele6 Jul '12 - 22:07 
the best
QuestionArticle datesmentorDaveAuld31 Jan '12 - 4:53 
Hi Chris,
 
Just a quicky, how come the first posted date is today, and it appeared as new on the home page, but yet there are message posts going back to 'ages ago' and the revision history shows first posting in July 2000?
 
Cheers,
Dave
Find Me On: Web|Facebook|Twitter|LinkedIn

Folding Stats: Team CodeProject


AnswerRe: Article datesadminChris Maunder31 Jan '12 - 5:41 
Just testing stuff. All good now.
cheers,
Chris Maunder
 
The Code Project | Co-founder
Microsoft C++ MVP

Generalbackground color change in List boxmembervinothkumar_Dhakshinamoorthy28 Jan '10 - 3:25 
Hi,
 
I'm having a Drop down list box in my HTML page. I'm loading the page with some values, the default value is displayed without any background color, but whenever i selected any other value the selected value displayed with blue background.
Is there any way we can control the backgournd color of the default value as blue.
 
Thanks,
D.vinoth
GeneralUsing JavaScript to handle drop-down list selectionsmemberpadolsky11 Aug '09 - 4:58 
I'm new to javascript so forgive me. I mainly use php but I can see how important using javascript can be. My question is, when the user selects one of the options of the drop down list, how can I get the value of the selection. In other words, I don't want the user going to a new URL, I just want the value of the selection. Because in the example given, the author uses the selection to change pages and I just want the value so that the user doesn't have to click on two buttons instead of one. Thank you in advance.
Generaldrop down multiple selectmemberLokesh Lal16 Jun '09 - 18:10 
Hi,
 
I have a question for you...
 
If i have about 600 options in select list multiple select
some thing like :
<select multiple="on" size="4">
<option1></option1>
...
<option600></option600>
</select>
 
So if i have to select 400 options out of this 600 options using javascript, it takes about 20 seonds to do so...
 
Do you know a better way to do this???
GeneralRe: drop down multiple selectadminChris Maunder17 Jun '09 - 3:06 
Lokesh Lal wrote:
Do you know a better way to do this???

 
Yes, don't offer 600 options. It's way too much.
 
One option is to have multiple selection boxes (eg Make of car, model of car). Choose an option from one box and it populates a smaller set of options in another box.
 
Another option is to use a tree control and group options into groups in order to allow your users to select main branches which will, implicitely, select the entries group underneath.
 
But the first step is to rethink what you are doing and attack it from a different angle.
 
cheers,
Chris Maunder
 
The Code Project Co-founder
Microsoft C++ MVP

GeneralRe: drop down multiple selectmemberLokesh Lal18 Jun '09 - 6:51 
Actually i am working on a travel portal and there i am populating all markets available in the drop list as user requirement. and if user selects all options then we add another option in the list with text all, however if user deselect one option and select remaining (i think there are ariund 580 or may be more markets) then on the reload of page or some other actions javascript takes a lot of time to select all options.
 
Any ways thanks for your suggestion, i'll try to figure out some alternate way of doing this.....
 
Lokesh
GeneralRe: drop down multiple selectadminChris Maunder18 Jun '09 - 6:51 
Split the locations into regions (States, countries, continents etc)
 
cheers,
Chris Maunder
 
The Code Project Co-founder
Microsoft C++ MVP

GeneralRe: drop down multiple selectmemberLokesh Lal18 Jun '09 - 18:00 
If i split the location in regions..then in that case if user have selected multiple markets, then i have to select all regions with in the market. And market is more granular than continents and countries. So i cannot restrict user to select whole country and then assign rates to them.
 
Thanks.
QuestionRequest:AnswermemberMember #393574418 Mar '07 - 22:41 
I have a dropdown box with state names and want district names to be displyed in another drop down box(district name corresponding to the selected option in the dropdown) show the code of this in javascript
 
Gitanjali_Dua@satyam.com
Questiondropdown(javascript)memberParul Chaudhary28 Jan '07 - 21:04 
I have a dropdown box with state names and want district names to be displyed in another drop down box(district name corresponding to the selected option in the dropdown)
 
and take both State Name and District Name and submit them to another page.
 

GeneralOpen/expand Dropdown by Scriptmemberguruk12317 Oct '06 - 4:00 
Hi,
 
I would really need to open (expand) a Dropdown menue externaly
 
So lets Say I say I have a Dropdown
 
<select size="1" name="unterkategorie"">
<option selected>Choose your Topic</option>
<option selected>Choose your Topic1<option>
<option selected>Choose your Topic2<option>
</select>
 
I would need something like external: Onclick=open("unterkategorie")
 
At the end I need that this Dropdown come OPENED like when I click with
my mouse on the closed Dropdown.
 
thanks....Christian
GeneralRefresh/Update dropdown list optionsmembermissyz17 Nov '04 - 7:23 
I have a drop down list with lets say city name. The last option other. When other is selected then a new page/window opens up to allow the user to enter in their city. Once they enter the city and click ok I add that city to a db. This is the same db I used to generate the dropdown list in the first place. The problem is I need for them to see their city in the list immediatly after they enter it and I can not refresh the page.
Questionnot using asp?memberangel_girl30 Dec '03 - 22:10 
only using javascript can it?
not using asp
 
this way is too hardly
 
Unsure | :~
 
maybe i can't express my idear exactly for my poor english. i am sorry
GeneralUse of arraysmemberAnonymous12 May '02 - 0:59 
Nice, but what if I want to use an array to fill in the list portion of a drop-down box, like this:
 
<HEAD>
var myArray = new Array();
 
myArray [0] = "Item 1";
myArray [1] = "Item 2";
myArray [2]= "Item 3";
 
</HEAD>
 
Now how would I iterate through that array and fill in the box, which is part of a table that I create later in the body section of a document. Can't figure this out.
 
Thanks.
 
Beginner
GeneralUse OnClick instead of OnChangesussDee A. Crouch17 Oct '00 - 10:19 
I use essentially the same technique in a self refering page to select criteria for displaying a database record. If you use the OnChange event to trigger the submit you will only get the event if the user clicks a new value (assuming that there is a currently selected value). If you use the OnClick event, the form will be submitted even if the value has not changed. This provides a "refresh/reset" functionality without using any additional real estate
GeneralRe: Use OnClick instead of OnChangememberSteven Gregg31 May '01 - 3:13 
Doing a similar thing. The trouble I have is that OnClick doesn't seem to work with IE5.5.
ie.
 
<HTML><HEAD></HEAD><BODY>
<FORM METHOD="POST" TARGET="viewer" NAME="actmsg2"
ACTION="http://machine/scripts/myisapi.dll/specific_action">
<INPUT TYPE="HIDDEN" NAME="userID" VALUE="Steevie">
<INPUT TYPE="HIDDEN" NAME="Language" VALUE="1">
<SELECT SIZE="1" NAME="newqualifier" önmouseover="window.status = 'Change qualifier'" >
<OPTION VALUE="new" önClick="alert('you clicked New')"> New </OPTION>
<OPTION VALUE="saved" önClick="alert('you clicked Active')"> Active </OPTION>
<OPTION VALUE="old" önClick="alert('you clicked Processed')"> Processed </OPTION>
</SELECT>
</FORM>
</BODY></HTML>
 
Infact, all the event driven stuff for <OPTION> doesn't seem to work. Any ideas?
GeneralRe: Use OnClick instead of OnChangememberAnonymous25 Oct '01 - 1:01 
Change the action to post and try it.
 


General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130523.1 | Last Updated 25 Jul 2009
Article Copyright 2000 by Chris Maunder
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid