1 Jul
2009

JQuery: Playing with Select (DropDownList/ComboBox)

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.

51 thoughts on “JQuery: Playing with Select (DropDownList/ComboBox)

  1. 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.

  2. 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.”

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

    2.  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.

  3. 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?

  4. @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)

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

  6. @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.

  7. 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*

  8. 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*

    1. 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.

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

      2.  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

  9. 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.

  10. 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.

  11. 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

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

  12. 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.

  13. 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

  14. Hi,

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

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

  16. 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.

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

  18. 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

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

  20. 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.

  21. 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.

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

Comments are closed.

Find me

RSS
Facebook
Twitter
LinkedIn