How Do I Preselect an Item in a Drop-Down List?

In HTML, it's pretty easy to preselect an item in a drop-down list. At design-time, or with a dynamic server page, at run-time at the server, all you need to do is add the selected attribute to the <option> element you want to select. If you want to select the item programmatically through JavaScript code, you'll have to follow a different route.

Let's consider the following drop-down list with first names:

<form id="frmPreselect" name="frmPreselect">
  <select id="lstNames" name="lstNames">
    <option value="John">John</option>
    <option value="Sam">Sam</option>
    <option value="Peter" selected="selected">Peter</option>
    <option value="Henri">Henri</option>
  </select>
</form>

The selected="selected" attribute/value pair makes sure the item for Peter is selected when the page loads in the browser.

If you want to change the selected item through JavaScript code, you can use the following method:

<script type="text/javascript">
  function PreselectMyItem(itemToSelect)
  {
    // Get a reference to the drop-down
    var myDropdownList = document.frmPreselect.lstNames;

    // Loop through all the items
    for (iLoop = 0; iLoop< myDropdownList.options.length; iLoop++)
    {    
      if (myDropdownList.options[iLoop].value == itemToSelect)
      {
        // Item is found. Set its selected property, and exit the loop
        myDropdownList.options[iLoop].selected = true;
        break;
      }
    }
  }
</script>

This code that loops through all the items in the drop-down list, checks out their value, and if that value matches the incoming parameter of itemToSelect, the drop-down item gets selected and the loop end. Don't forget that JavaScript is case-sensitive, so you'll have to type in the name exactly the same as it appears in the value attributes of the <option> element.

To execute this code, you'll have to call the PreselectMyItem method, and pass it the value of an item you want to preselect. You can, for example, add a text box and a button to your page, and ask the user for a name, which then gets preselected:

    <option value="Henri">Henri</option>
  </select>
  <input type="text" value="" name="txtName" id="txtName">
  <input type="button" value="Set Name" name="btnDo" id="btnDo"
       onclick="PreselectMyItem(document.frmPreselect.txtName.value)" />
</form>

When you type a name, and then click the Set Name button, the text you typed in the textbox txtName will be passed to the PreselectMyItem method, and if the item is found, it will be selected. Make sure you use proper casing in the name, as the code is ase sensitive.

You can test out a running example of this code.


Where to Next?

Wonder where to go next? You can read existing comments below or you can post a comment yourself on this article .


Consider making a donation
Please consider making a donation using PayPal. Your donation helps me to pay the bills so I can keep running Imar.Spaanjaars.Com, providing fresh content as often as possible.



Feedback by Other Visitors of Imar.Spaanjaars.Com

On Friday, January 06, 2006 7:47:44 AM Vinotth Joseph D said:
Excellent
On Thursday, April 20, 2006 5:52:42 PM Joe P said:
awesome. exactly what i was looking for. simple and elegant code.
On Friday, April 28, 2006 11:57:58 AM Mark van Wyk said:
Very cool web site. Default fonts are just a bit tiny. Really nice to read code clearly.
On Friday, April 28, 2006 7:17:53 PM Imar Spaanjaars said:
Hi Mark,

Thanks; I am glad you like this ite.

When you say too tiny font, are you referring to the text in general, or to the code examples. Would a scalable font help (that is, where you control the font size from within your browser)?  Using resizable fonts is on my list for some time, but I haven't had the time to fix that yet.....

Please let me know what you think.

Cheers,

Imar
On Wednesday, May 24, 2006 3:40:49 PM Mike Lester said:
Great example.
I was wondering if there is any way to automatically expand the list (as if you selected the down arrow) after the value is set??
On Wednesday, May 24, 2006 4:16:16 PM Imar Spaanjaars said:
Hi Mike,

As far as I know, there's no way to do this. This is something that's controlled by the browser and I don't think there's a way to open the drop down through script.

Cheers,

Imar
On Tuesday, July 04, 2006 12:03:41 PM umesh kumar said:
very useful code snippet.. Thanx!!
On Thursday, July 20, 2006 4:30:13 PM leon said:
Brillant example. Looked all over and you code was exactly what I had been trying to do.

Thanks for showing me the way!
On Thursday, January 25, 2007 1:53:35 PM juliano said:
Hello, thanks for sharing the script.
I 've trying to dynamically create a preselected select element based on the key of an associative array in input. That is pretty useful to handle directly database primary keys that does not forcely follows the array index order.

function getSelectElement(options, tobeSelected) {
   var select = document.createElement("select");
   var option, i;
   // for each key/value
   for (i in options) {
       option = document.createElement("option");
       option.value = i;
       option.text = options[i];
       if (tobeSelected != null) {
          option.selected = (i == tobeSelected);
          try {
              select.add(option, null); // standards compliant
          }
          catch(ex) {
              select.add(option); // IE only
          }
   }
   return select;
}

examle:
var types = new Array();
types["7"]="tall";
types["1"]="taller";
types["15"]="tallest";

document.body.appendChild(getSelectElement(types, "15"));

This works great in IE7 ("tallest" is preselected), but fails in IE6, as it selects always the previous option to the one that should be ("taller"in the example).
Anyone having any clue?
On Thursday, January 25, 2007 1:58:26 PM juliano said:
Sorry, if someone trying my last post, please discard one extra bracket here (copy-pasting gap):

if (tobeSelected != null)    ====>    {    <====  to be removed
          option.selected = (i == tobeSelected);
On Wednesday, April 25, 2007 9:43:52 AM kiranvemula said:
Excellent. This is what i am looking for.
On Wednesday, October 24, 2007 8:49:24 PM Nick said:
This code works in IE and Firefox but not Safari
On Wednesday, October 24, 2007 8:59:57 PM Imar Spaanjaars said:
Hi Nick,

First of all, this article is from 2004, long before Safari hit the streets.....

Secondly, are you sure about this? Can you define "not [in] in Safari"? Do you get an error?

AFAIK, this code only uses standard DOM methods but I'll be happy to hear where it goes wrong so I can fix it...

Cheers,

Imar
On Wednesday, October 24, 2007 9:15:59 PM Nick said:
Oh -- I didn't know when Safari came out and I wasn't trying to insult your code, just wanted to make you aware.  I just mentioned it because I was actually having a problem with my site that essentially made it unusable in Safari and I was searching for a solution.  I figured out my issue, but I'm pretty sure this is more of an issue with Safari than with your code.  

On my site I had a function that would basically set selected=selected in an If statement within a loop.  

Something like this:

alert(x[0].item(i).selected);  ->> returned false
x[0].item(i).selected = "selected";  
alert(x[0].item(i).selected);  ->> returned true

So it appeared that it did the right thing, but it never actually selected the item.  I finally had to change some logic around on mine to get things working.

Anyway, there's no error... if I type "Sam" and click the button it doesn't change the selected value in Safari like it does with IE/Firefox.
On Wednesday, October 24, 2007 9:31:56 PM Imar Spaanjaars said:
I didn't feel insulted; I just wanted to make sure you understood this article shows pretty old code with no guarantee that it's going to work on modern browsers.

Also, I lied a little as Safari was released with Mac OS v10.3 in October 2003....

I can't tell you why this doesn't work on Safari right now, but I'll check as soon as I am close to a Mac (don't have one at home).

I am sure you already checked this, but did you type Sam and not sam?


Imar
On Wednesday, November 07, 2007 12:04:46 PM Basem said:
thanks a lot
code is very helpful
On Tuesday, February 19, 2008 12:15:13 PM white said:
hi i have the same problem as nick does and  this thing i.e x[0].item(i).selected = "selected" or x[0].item(i).selected = true; doesnot work any safari
any clues  to solve this bug
it will be e gr8 help
On Tuesday, February 19, 2008 12:50:24 PM Imar Spaanjaars said:
Hi white,

Why are you using () and not []?

Maybe it;s easier if you post this on a forum like p2p.wrox.com.


Imar
On Wednesday, April 22, 2009 8:28:34 PM vlzvl said:
nice catchy code but it didnt worked for me (at first & at mozilla)
I solve the issue putting a delay for execution etc.

setTimeout(' document.getElementById(\'myid\').selectedIndex=2;  ',10);

this worked for my & in my (heavy) page
tx
On Friday, August 14, 2009 9:00:03 AM amit soni said:
thanks for nice work i was looking for the same
helped me a lot..
On Sunday, December 06, 2009 9:39:03 PM Jeromy said:
Thanks so much, that's exactly what I needed in order to pre-select multiple options for a select box.
On Wednesday, September 07, 2011 1:54:11 AM Alok said:
For some reasons, I can't use:

body onload="PreselectMyItem('John');"

I tried calling this function in either of the following ways, but it didn't work:

script type="text/javascript"
window.onload="PreselectMyItem('John');"
/script

-- or --

script type="text/javascript"
PreselectMyItem('John');
/script

This only works when the function in called from within the body tag. Is there any alternative for this.

Thanks in advance.

PS - I had to remove the angled bracket as I was unable to post a comment
On Wednesday, September 07, 2011 7:32:45 AM Imar Spaanjaars said:
Hi there,

Hard to say without seenig the full code. Try posting this on a forum such as http://p2p.wrox.com/index.php?referrerid=385 and be sure to provide the full code or people won't be able to help.

That said, this code is 7 years old. You're probably better off looking at jQuery as it has functionality to handle onload in a generic way as well as selecting items in a list.

>> PS - I had to remove the angled bracket as I was unable to post a comment

Correct ;-) That's why the label next to the text field says:

>> (Plain text only; no HTML or code that looks like HTML or XML. In other words, don't use < and >.

Cheers,

Imar
On Wednesday, September 07, 2011 8:44:02 AM Alok said:
Hi Imar,

I have used the code exactly as can be seen in the demo with the exception that I tried to call the function using script as mentioned above and not from body onload.

I tried to debug this by calling the function from various locations but none of them worked. It only works if called from body onload.

As for the jquery, I will have to research it. I don't know much about javascript & jquery.

Thanks anyways.
On Wednesday, September 07, 2011 8:49:27 AM Imar Spaanjaars said:
Now I am confused....

>> with the exception that I tried to call the function using script as mentioned above and not from body onload.

and

>> It only works if called from body onload.

While in your first message you said:

>> I can't use: body onload="PreselectMyItem('John');"

giving me the impression that that doesn't work for you.

So, please, let the code do the talking: post your full page at the forum I mentioned in an apprpriate category and I'll take a look.

Cheers,

Imar

Talk Back! Comment on Imar.Spaanjaars.Com

I am interested in what you have to say about this article. Feel free to post any comments, remarks or questions you may have about this article. The Talk Back feature is not meant for technical questions that are not directly related to this article. So, a post like "Hey, can you tell me how I can upload files to a MySQL database in PHP?" is likely to be removed. Also spam and unrealistic job offers will be deleted immediately.

When you post a comment, you have to provide your name and the comment. Your e-mail address is optional and you only need to provide it if you want me to contact you. It will not be displayed along with your comment. I got sick and tired of the comment spam I was receiving, so I have protected this page with a simple calculation exercise. This means that if you want to leave a comment, you'll need to complete the calculation before you hit the Post Comment button.

If you want to object to a comment made by another visitor, be sure to contact me and I'll look into it ASAP. Don't forget to mention the page link, or the QuickDocId of the document.

For more information about the Talk Back feature, check out this news item.