Link to home
Start Free TrialLog in
Avatar of bitt3n
bitt3n

asked on

maximum number of options in a dropdown menu

I have a list of about 2000 locations (Country-Region-City) and I am considering using them as options in a dropdown menu with one option preselected. I would like to know:

1) Is it feasible to put this many options in a dropdown menu? I don't imagine the total size in K is that large, but I am not sure that is the only factor to consider. Perhaps there are usability issues of which I am not aware if the user's computer is slow. I have never seen a site use a menu this large.

2) Is there a better way to do achieve the same result? I imagine there is some way to use javascript to set up 3 dropdowns for country, region and city (which would each be much smaller than 2000), and then preselect each. However I have no experience with that and do not know if it would even work. Obviously the selectable list of cities would depend on the list of regions which would in turn depend on the selected country. Is this an option or is there something else better?

Thanks for your help.
Avatar of Tomeeboy
Tomeeboy
Flag of United States of America image

Well, I can tell you that it would definitely work to have 2000 items in a single drop down box.  I've seen almost 40,000 in a dropdown box before :)

As for a better method of organizing your dropdown data, you could potentially link multiple dropdown boxes via javascript, as you mentioned.  I would think the best way to organize them would be to first select a country, then have a list of cities/regions come up.
Avatar of UnexplainedWays
UnexplainedWays

I can imagine that 2000 could be a bad idea, could take a while for the user to find what there after.

I dont mind the 3 drop down menu's idea.

Try this link: http://www.realestate.com.au/cgi-bin/rsearch?a=sf&s=nsw&t=res&snf=rbs
What it has is a textbox and the more you type, the more it searches though the list box for you.  I would like a solution that filter's the results to make it easier to find, however that could get quite tricky.
Here is some example javascript for the tiered dropdown idea you were thinking of implementing, it should be helpful if you decide to go that route (which I think you probably should, to save the end user a lot of hassle):

http://fairfieldconsulting.com/js_multipleSelects.asp
Yes, definitely split it up your drop down menu. A large list will cause usability problems. Most normal users will get frustrated scrolling through a very large list.

You can use JavaScript & the DOM to setup 3 drop downs as you have described. To do this you will need to put your countries into an array. For each country you will need to create an array of regions. Then for each region you will have an array of cities.

You can then adapt the following code to dynamically create the drop downs:
var countries = document.formName.country; // country drop down in form
countries.options[countries.options.length] = new Option("Text in drop down here", "Text in value field", false, false); // add a new option item

You will obviously need to use an appropriate loop for the code above based on how you have created your arrays. The 2 false parameters are to indicate that the option is not the default selected or current selected option item. If you did want to make the option item the default or currently selected item you would you change the corresponding parameters to true.

Remember, you can look at the source code from that website to learn how they do it.  It's a nice bit of javascript - I've never seen that functionality implemented before.
Avatar of bitt3n

ASKER

the same site mentioned by Tomeeboy (http://fairfieldconsulting.com/js_multipleSelects.asp) has another way to do the multiple menus (http://fairfieldconsulting.com/asp_multipleSelects.asp).

That latter article says of the two approaches: "One approach [the first one] entails using client-side JavaScript arrays (please see article under the JavaScript tutorials) but this approach may not work well when there are many records or when the data is dynamic. In these cases, using server-side code to control the data flow most likely is the best approach."

Either approach I use, I think I will want to populate the dropdowns via MySQL query. If I use the Javascript version it appears that I will SELECT the countries into an array, then run through this array with SELECT to create each region array, and then run through the country array *and* the region arrays with SELECT to create each city array.

It seems like I may want to use the ASP_multipleSelects version over the JS_multipleSelects version in that I could only generate the arrays I need (eg, if user chooses USA, I only have to get regions in USA, and then if user chooses Florida, I only have to get cities in Florida). Would this in fact be better? (of course only know PHP so I would do a PHP version, but I think I get the idea).

Thanks for all the suggestions so far, I greatly appreciate your help.
Yes the ASP version (or PHP) would bring back less data eventually, but you'd be sending more HTTP requests and hitting the database more often.

Is your app for a fast intranet?  If so, just load all the data up in the first place - a bit of bandwidth won't hurt.

Also, consider making it static data, via a javascript include file, rather than hitting the database each time.  How often do countries and regions and cities change, anyway?  Even if your database changed its countries, regions, and cities every day, you could have a script update the include file each night at 4am.  That way the js file would get cached and would barely need to hit the webserver, let alone make three calls to the database each time.
You can have an interlinked three dropdown boxes with country dropdown and city, selection of the former loads the corresponding children in the latter in that order.

However, ensure that too many items in the dropdown list may eventually freeze the browser, unduly load the Internet Pipe and the server.

You can use OPTGROUP tag to format items within the dropdown and use Ajax Tricks to do little paginations within the dropdwon like  showing 25 countries and then use OptGroup to display 'Next 25' and when this is selected, use XmlHttpRequest to load the next 25 countries in this dropdown.

Did this attend to your query?
Avatar of bitt3n

ASKER

@crimson117

That makes sense to me. My app is not for an intranet, but the amount of the data isn't outrageous. Other things being equal I think the JS version makes sense then. My practical considerations are:

1) I know PHP but I have done almost nothing with JS except copy paste scripts
2) The page in question won't get hit very often: usually only when the user registers or moves to a new location. Thus it if it's a bit inefficient that won't have a major impact on the database (hopefully).

I think the next thing I need to do is get familiar with how much effort it will take to learn the necessary JS to implement that solution. Then I will decide whether to use JS or PHP. I assume one of these books would tell me all I need to know (or if you have a recommendation?):

http://www.amazon.com/gp/product/0072227907/qid=1141102923/sr=1-1/ref=sr_1_1/103-6216200-6932636?s=books&v=glance&n=283155
http://www.amazon.com/gp/product/007226134X/qid=1141102923/sr=1-2/ref=sr_1_2/103-6216200-6932636?s=books&v=glance&n=283155

@deepaknet

I don't know Ajax so I think that might be over my head. How many elements might you estimate would need to be in a dropdown before such a method would be necessary?
Sorry, don't have any good recommendations on JavaScript books :)  Personally, I'd get started with free web tutorials, then buy a javascript reference book.  But books can have good tutorials, as well.  Try skimming through some at the bookstore.  You may even find one with just such an example all ready for you to learn.
Ooo, here's a good script. Pick a country and it filters the state dropdown accordingly.  It also provides a blank text box if no state dropdown choices match that country. You can edit the country/state data or you could write it dynamically with php based on a database query.

http://javascript.internet.com/forms/country-state-drop-down.html
Some screenshot for the dropdownlist powered by AJAX. http://www.codeproject.com/aspnet/ajaxdropdownlist.asp

(You need not get locked by ASP.NET. The code is simple 5 lines using www.scss.com.au/family/andrew/webdesign/xmlhttprequest/  (xmlhttprequest.js is downloadable from here))

Also check out this discussion: http://www.thescripts.com/forum/thread94897.html
Avatar of bitt3n

ASKER

@crimson117

hm.. that does look very close to what I want. I assume the two-letter abbreviations are the values and the full names are the options?

is it an easy change to add the third selectable field for city? obviously I need

<select id='citySelect' name='city'>

in the form, and

<select id='stateSelect' name='state'>

will become

<select id='stateSelect' name='state' onchange='populateCity()'>

and I need to add a third tier to the database of the form

var state = '\
US:AK:AN:Anchorage|\
US:AL:MB:Mobile|\
US:AZ:PX:Phoenix|\
';

However it would be a huge help if you might be able to show how to modify/create populateState() and populateCity() to get the third dropdown working.

Thanks again for finding the script. This is very much like the ASP version (http://fairfieldconsulting.com/articles/asp_multiSelects_6.asp) but it appears JS is optimal
Avatar of bitt3n

ASKER

@crimson117

I did some more hunting based on your suggestions and found a 3-tier one @

http://www.sitepoint.com/forums/showthread.php?t=350291

This appears to be what I want. Does this look a workable variant of the script you found (ie no obvious drawbacks that I can't see because I don't know JS)? Thanks again.
Avatar of bitt3n

ASKER

hm.. I guess the thing I really need to know is how do I pre-select a given Country/Region/City combo based on $_POST variables. Your version had a handy way to do that with:

// If you have PHP you can set the post values like this
//var postState = '<?= $_POST["state"] ?>';
//var postCountry = '<?= $_POST["country"] ?>';

So I either need to figure out how to add that functionality to my 3-tier script or modify the 2-tier one to make it 3-tier..
First give the <select> an id:   <select id="country" (etc....)>

then you could a bit of javascript at the end of the page, just above </body>:

<script type='text/javascript'>
 document.getElementById("country").value = '<?= $_POST["country"] ?>';
</script>

Regarding your recommendation for a JavaScript book - I code in JavaScript all the time and couldn't get by without this one:

JavaScript: The Definitive Guide - David Flanagan
http://www.amazon.com/gp/product/0596000480/qid=1141111767/sr=2-1/ref=pd_bbs_b_2_1/103-8840625-8439819?s=books&v=glance&n=283155 

It has been highly recommended on several online forums and from other books so it is definately one worth checking out...
Avatar of bitt3n

ASKER

@crimson117

hm.. that seems to work for the Regions, but I cannot get it to work for Country and City (perhaps because of the way the menus are generated from the Regions menu?) If you can tell me how to make it select Country and City the way it selects Region, I would have everything I need. Thanks again. Here is the code I am using based on your suggestion:

<form>
Region&raquo; <select id="region" onchange="set_country(this,country,city_state)" size="1" name="region">
<option value="" selected="selected">SELECT REGION</option>
<option value=""></option>
<script type="text/javascript">
setRegions(this);
</script>
</select>
Country&raquo; <select id="country" name="country" size="1" disabled="disabled" onchange="set_city_state(this,city_state)"></select>
City/State&raquo; <select id ="city" name="city_state" size="1" disabled="disabled" onchange="print_city_state(country,this)"></select>
</form>
<script type='text/javascript'>
 document.getElementById("region").value = 'North America';
</script>
<script type='text/javascript'>
 document.getElementById("country").value = 'United States';
</script>
<script type='text/javascript'>
 document.getElementById("city").value = 'Alabama';
</script>
Oh, I see.  The values for country and city do not exist until you pick a region - the dropdowns start out empty.  By putting the script where I advised, it only gets run when the page is first loaded.

We'll need to set the value each time the dropdown is populated, and then call the function as to simulate the user having actually clicked the selection.

In set_regions, add this as the last line of e script:

  set_country(region,country,city_state);


In set_country, add this just before the closing } in the first IF statement:

  oCountrySel.value = 'United States';
  set_city_state(oCountrySel,oCity_StateSel);


In set_city_state, add this just before the closing } in the first IF statement:

  oCity_StateSel.value = 'Alabama';
  print_city_state(oCountrySel, oCity_StateSel);


Avatar of bitt3n

ASKER

hm.. I made the changes but I am still not able to select Country and City. I probably did something stupid, perhaps you can point it out.

Here is the code. Is adding 'oRegionSel.value = 'North America';' in the first function necessary? At first I left the 'document.getElementById("region").value = 'North America';' line in the form, because otherwise the region is not specified anywhere so it definitely won't work. I then removed that line and added 'oRegionSel.value = 'North America';' directly above 'set_country(region,country,city_state);' in the first function, but still it didn't work.

function setRegions()
{
      for (region in countries)
            document.write('<option value="' + region + '">' + region + '</option>');
      set_country(region,country,city_state);
}

function set_country(oRegionSel, oCountrySel, oCity_StateSel)
{
      var countryArr;
      oCountrySel.length = 0;
      oCity_StateSel.length = 0;
      var region = oRegionSel.options[oRegionSel.selectedIndex].text;
      if (countries[region])
      {
            oCountrySel.disabled = false;
            oCity_StateSel.disabled = true;
            oCountrySel.options[0] = new Option('SELECT COUNTRY','');
            countryArr = countries[region].split('|');
            for (var i = 0; i < countryArr.length; i++)
                  oCountrySel.options[i + 1] = new Option(countryArr[i], countryArr[i]);
            document.getElementById('txtregion').innerHTML = region;
            document.getElementById('txtplacename').innerHTML = '';
            oCountrySel.value = 'United States';
            set_city_state(oCountrySel,oCity_StateSel);
      }
      else oCountrySel.disabled = true;
}

function set_city_state(oCountrySel, oCity_StateSel)
{
      var city_stateArr;
      oCity_StateSel.length = 0;
      var country = oCountrySel.options[oCountrySel.selectedIndex].text;
      if (city_states[country])
      {
            oCity_StateSel.disabled = false;
            oCity_StateSel.options[0] = new Option('SELECT NEAREST DIVISION','');
            city_stateArr = city_states[country].split('|');
            for (var i = 0; i < city_stateArr.length; i++)
                  oCity_StateSel.options[i+1] = new Option(city_stateArr[i],city_stateArr[i]);
            document.getElementById('txtplacename').innerHTML = country;
            oCity_StateSel.value = 'Alabama';
            print_city_state(oCountrySel, oCity_StateSel);
      }
      else oCity_StateSel.disabled = true;
}
ASKER CERTIFIED SOLUTION
Avatar of crimson117
crimson117

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of bitt3n

ASKER

OK great I got it working thanks!

I think I found a small bug in the code though and I am wondering if you can tell me how to fix it. When the user de-selects the region (so that no region is selected), the country (middle) dropdown becomes unselectable, but the city dropdown merely becomes blank and is not unselectable (ie, it still drops down). This isn't a big deal with the black formatting of the dropdowns in the example, but on my page it looks ugly because the unselectable dropdown is gray, and the selectable (but blank) dropdown is white.

It's a minor problem but I would like to fix it if possible. Thanks again for all your help.
In set_country change "else oCountrySel.disabled = true;" to "else {oCountrySel.disabled = true; oCity_StateSel.disabled = true;}"

Avatar of bitt3n

ASKER

@crimson117

everything works 100%. thanks for your help

thanks also to the other respondents -- I learned a lot in this thread