JQuery: Playing with Select (DropDownList/ComboBox)

July 1st, 2009

Why oh why did the HTML overlords call their Combo Box/DropDownList a SELECT?  Then call the items in the list OPTIONS?  It isn’t like there weren’t a plethora of other names for the widget.  Then it could have been consistent anyway.

Oh well.

It seams that each time I start a new project I have to relearn how to grab values out of a DropDownList – I mean “select element”.  Anyway, I’m trying to get this down before I go nuts and have to learn it all over again.

Basic Select

First off, here is the basic html I’m talking about:

   1: <select id="ComboBox" >
   2:       <option value="1">Value 1</option>
   3:       <option value="2">Value 2</option>
   4:       <option value="3">Value 3</option>
   5:       <option value="4">Value 4</option>
   6:       <optgroup label="Group1">
   7:         <option value="5">Value 5</option>
   8:         <option value="6">Value 6</option>
   9:         <option value="7">Value 7</option>
  10:         <option value="8">Value 8</option>
  11:       </optgroup>
  12:     </select>

Nice and simple.  Now, the basic things you want to do with said select statement:

1. Get the value of the selected item.

2. Get the text of the selected item.

3. Find out when the value changed

4. Programmatically set the selected item.

5. Modify the list.

Most of those are very easy with JQuery, but one is slightly strange. Lets go through these one by one:

1. Get the value of the selected item

This is the easiest.  Use the val method.  All done.

   1: $("#ComboBox").val()

2. Get the text of the selected item

You would think this would be easy as well, but it isn’t.  You cannot just use the text() method on the combobox.  That will give you the text values of all of the options in a single string.  Not what you want.  The trick is to use the :selected query modifier on the option.

   1: $("#ComboBox option:selected").text()

Now, you might be tempted to use the ‘>’ (means direct descendent of) between the #ComboBox and the option — don’t.  If you look at my example above, that code will only work for options not in optgroup nodes.

3. Find out when the select value changed

This is also rather easy with JQuery.

   1: $("#ComboBox").change(function() { /* do something here */ });

4. Programmatically set the selected item.

   1: $("#ComboBox").val(2);

5. Modify the list.

Modifying a select element is not fundamentally different than modifying any other element in the dom, but there are a few basics here to keep in mind. Mainly: try to avoid using the dom directly.  Create html strings instead.

Clear the list:   $(“#ComboBox”).html(“”);

Add to the list: $(“<option value=’9’>Value 9</option>”).appendTo(“#ComboBox”);

Simple as that.

Chris Brandsma

  • http://artlung.com/ Joe Crawford

    Nice tips.

    You say “try to avoid using the dom directly” — why?

    Other gotchas of select boxes: select that allows multiple selected options behaves differently.

    Also, the val() of an option that does not have a “value” attribute is the the text() string.

  • Jason

    The reason it’s called “select” instead of a “DropDownList” is a) Microsoft, thankfully, doesn’t get to name things all the time, and b) HTML is supposed to be presentation independent. Calling it “select” allows the client to display the list of options however they want. Same reason that “i” and “b” are deprecated in favor of “em” and “strong.”

  • http://www.jaceju.net/blog/?p=608 ??????? » [Web] ????

    [...] JQuery: Playing with Select (DropDownList/ComboBox) [...]

  • Mark Puddephatt

    Hi,

    I am looking for a way to trigger a dropdown to clear any value that has been selected from it, so it returns to its default state where nothing is selected.

    The best way i’ve found to achieve this is to prepend a blank option to the dropdown and then select that blank option:

    $(“#dropdown”).prepend(“”);
    $(“#dropdown option:first-child”).attr(“selected”,”selected”);

    But ideally I would prefer not to have a blank option in the dropdown selector so that I dont have to validate the user to ensure they are not submitting a blank value.

    What i’m wondering is if there is a simple way to tell the dropdown to return to the state where nothing is selected, e.g. if there was something like (“#dropdown”).reset – any ideas?

  • Mark Puddephatt

    @Mark Puddephatt

    Whoop a bit of my script seems to have got lost, it should be:

    $(“#dropdown”).prepend(“”);
    $(“#dropdown option:first-child”).attr(“selected”,”selected”);

    (without the spaces on the option tags)

  • Mark Puddephatt

    OK sorry about this, but the comments box doesnt like html code! But the prepend has an option tag inside the quotes…

  • http://www.elegantcode.com Chris Brandsma

    @mark, as far as I know, a dropdown ALWAYS has a selected item. By default it is the first item in the list. So your dropdown needs a blank item in it if you want a ‘nonselected’ option.

    The alternative is to not use a dropdown at all. Instead use a textbox that links to a hidden div that dispalys when the textbox is selected/clicked. The JQuery Calendar control does this.

  • sebastien

    Hi, I’m french and i have a problem. Maybe coud you help me.
    I use combobox
    here : http://jquery.sanchezsalvador.com/jquery/page/jquerycomboboxapi.aspx

    And i put an onchange on my select. With “onchange”, a “option” is like an “a href”.

    But there is no result.
    Could you help me please ?

  • http://openlandscape.wordpress.com Jacques

    Very consise article, with everything I wanted to know about jQuery and select-options or drop down lists. Thanks so much!

  • Nknnada84

    I m NK NANDA,i want to know more about details.with demo

  • Nightstalker98

    EXCELLENT! Thank you so much :)

  • Bondguy

    how can we remove certain options from Select list based on the text value of that option ?

    (note: it is not just the selected option , but some of the options need to be removed based on the text)

    e.g. I want to remove options that have the text starting with *

    *one*
    two
    three
    *four*

  • Bond

    how can we remove certain options from Select list based on the text value of that option ?

    (note: it is not just the selected option , but some of the options need to be removed based on the text)

    e.g. remove any option that starts with the text *

    *one*
    two
    *three*
    *four*

  • Simbu 94 It

    i have two combo box from the first combo box i am loading the second combo box when i select the items in second combo box it’s always showing the first element it’s not getting my selected item.

  • http://www.facebook.com/people/Samuel-Anderson/1273021017 Samuel Anderson

    I have only just started with jQuery but this may work for you:

    $(‘#tryit option’).each(function(){ if($(this).text().indexOf(‘*’) > -1) $(‘#tryit option’).remove(‘:contains(“‘ + $(this).text() + ‘”)’); });

    You may want to try that, i haven’t tested it, but from the documentation it says it should work.

  • Bondguy

    thank you so much – you will master jquery pretty well – this code just worked sweeeet!

  • http://www.facebook.com/shehriyari Shahriyar Imanov

    Part 5 – Modify the list:

    For “Clear the list”, this would suffice: $(“#ComboBox”).empty();

  • Mike

    Hello Chris,

    I have been trying to implement the nice tips in your tutorial to resolve a dropdown problem.I am using jquery.validate.js plugin.

    I hope you can help me with me this.

    How do I make one element required based upon a dropdown list’s selected OPTION?

    ex:

    Please note that the select and the textbox are arrays. I have addNewRow and DeleteRow methods to dynamically add/delete rows.
    ___________________________________________________
    Books and Titles 

    Choose One
    jQuery
    PHP
    Perl
    Other – please specify name

    If “Other – please specify name” is selected, then the input with name “otherbook[ ]” must be required.

    I tried as below but it does not work:

    rules:{
    “otherbook[]“: {
    required: function(){
    return $(“#books option:selected”).text()==”Other – please specify name”;
    }
    }

    I just can’t figure out how to do this.

    Appreciate your help and thanks in advance.

  • http://blog.iajlan.com ajlany

    Hello Chris,
    I hope your still reading this thread
    I need some help with my code
    I have two dropdown lists and each option has a value. What I want is to get the value of both selections and compare them and show the result to the user.
    would appreciate any hint
    ibrahim

  • David

    Great post!! I’m working on a project requiring this sort of functionality. My biggest challenge is going to getting the value from multiple dropdown…er “select” boxes based upon class only (dynamically generated, so no can’t hard-code id’s). Any thoughts? Thanks.

  • Msvc6

    $(‘#selename,#selname’).live(‘change’,function(){
    if($(‘#selename’).find(‘option:selected’).val()===$(‘#selname option:selected’).val()){
    $(‘#myDiv’).text(‘equal’);
    }else $(‘#myDiv’).text(‘not equal’);
    });

  • Deepak

    HI can any one tell me how to get all the combobox value into an array using jquery

  • Inojhj

    wsdadsd

  • Inojhj

    wsdadsd

  • http://profiles.google.com/slavagtrgt Slava GTRGT

    Nice

  • Anonymous

    Cool comment Form

  • Chris Emerson

     i and b are NOT deprecated in favour of anything, only u is deprecated. Which you use depends on the context / situation.

  • Chris Emerson

     Also, the reason it isn’t called DropDownList or anything like that is that the select element can have a size, which turns it into a list box rather than a drop down list.

  • Anonymous

    Thanks, this is great — simple and to the point. jQuery is amazing.

    Tip:

    if you want to do this on more than one element, rather than specifying the ID, just do this:

    $(‘select’).change(function() {
        var selectedOption = $(this).find(‘option:selected’);
        var selectedOptionValue = $(selectedOption).val();
        var selectedOptionText = $(selectedOption).text();
       
        alert(“You selected” + selectedOptionText + “Value: ” + selectedOptionValue);
    });

    Or obviously if you just wanted to target only certain dropdowns, change first line to:

    $(‘select.className’).
    or
    $(‘#containerElement select’).

    or whatever.

    Hope someone finds this useful.

    dustin

  • Borgulas

    Awesome, #4 was just what I was looking for. Thank you for sharing.

  • Jono

    good stuff

  • Dfgh

    nice

  • Bimal B

    Very Useful..  Cheers..

  • http://www.plik-u.com plikucom

    nice to paly with jquery

  • Abhay Malviya

    Hi,

     You steps are looking so good. But its too helpful if you upload the hole code also.

  • Alexey

    $(‘#edit_tag_type’)[0].options[type].selected = true
    this string change selected item, where type is number of intem.

  • http://www.facebook.com/profile.php?id=1637750949 Wes Matchett

    Excellent article.  It allowed me to get my select working with jquery very quickly.  However, I am lost on one missing item. Is it possible to add an optgroup using jquery.  ie. build your example entirely from jquery?  My select is geographic areas (countries) that contain subgroups (states for instance).  I am starting with an empty select and adding everything based on an array of geo objects.

  • Vambara8

     i have  53 options in my select. I need to go to the 34th week. I was able to select that option using $(“#ComboBox”).val(34);. But the dropdown is customed to show only 10 entries. so its showing from 1 – 10 .but i need it to show from 30-40.Please help

  • Muziraluca

     how controle a dropdownlist in the case when i select province in dropdownlist1
    it give there district on the dropdownlist2

  • http://www.raghibsuleman.com/ raghibsuleman

    good work thanks for sharing….

  • Chauhanvipul87

    thanks a lot ..

  • http://www.facebook.com/romanmh Román Manuel Huerta Manrique

    Really nice

  • Dheeraj Jaiswal

    usefull statements, very good descriptions how to play with select using jquery………..

  • Renee V

    Hi Chris,
    Code seems simple & straightforward. But I can’t seem to make it work.

    I used
    $(#DropDownList1″).val(2);
    alert(“#DropDownList1″).val());

    The message was undefined. 

    Here is my problem. I need to get StatusCode from Main table, look up the Status on StatusDesc Table and show the Description on a dropdown. All of this to be done progammatically.  Meaning, I have to pass on the StatusCode to the .click function… Simple, I’ve done it in other programming languages. But asp.net is killing me. did not work, so I turned to jQuery.

    Any insights?
    Thanks in advance!
    Renee

  • Evan

    It lets you “select” an “option” – DropDownList and ComboBox imply absolutely nothing about the function of the element.

  • http://ymabyts.blogspot.com/ Ymabyts

    fds

  • http://ymabyts.blogspot.com/ Ymabyts

    sorry for earlier. nice tip. thanks for sharing. 

  • Greg

    excellent article Chris.
    i seem to be having troubles using the code in item #4
    it doesnt change what i see (ie9 and ff)
    however, oddly enough
    .. alert($(
    alert($(
    ‘#unitPrefFlowLiquid option:selected’).text());

    does show me what i expect. Just it doesnt change the text.

    does show me what i expect. Just it doesnt change the text.

  • Sam Naseri

    Hi,

    this is a great article. But it lacks some more advanced scenarios that I think worth adding. One is about how to deselect an option and the other one is how to remove all options.

  • Dsfdfasdfsdf

    sdfsdafsdafsdfsdfsdfsdf

  • Gopikrsna Ch

    GoodDay !
    From the above mentioned example , I have selected “VALUE1″ ….
    it is displaying twice.
    How to hide this.

blog comments powered by Disqus