jQuery Select Example

Now that I am working a lot more with jQuery I thought I would start posting little examples of why I enjoy using it so much. If you are looking for a full on beginner or selective tutorial you should head over to the tutorials section on the jQuery site, it is packed with great stuff. This first example is a short one but to me is the main reason I have been using jQuery so much lately. Just keep in mind when I am going through these examples that I am no JS expert so there may be better ways to accomplish the task at hand.

Everyone has dealt with a select box (drop down) at one point or another right? One thing I really hate about JS is how much code I have to write just to accomplish what should be a simple task. Here is the way I would of done it in the past. In our example we have a list of developers in a select menu. We explicitly set an onChange event handler (not a good practice more on that another time) that calls our onSelectChange method. The problem now is that you have to grab the element from the dom, find the selected index and write all this code to get the values and text. I just don’t have fun writing this and you can probably see why. If there is a better way that is my fault and while this would work its just no fun for me.

Now on to the fun part. The first thing we need to do is include the jquery library and create a ready function. We also have our list of developers and our goal is to write out what developer the user selects every time the selection changes.



The first thing we need to do is to notify our application that the user changed their selection. To do that we can use a jquery change event. To use this event we must first have a jquery object. This is really where the beauty of the code lies, almost everything is returned as a jQuery object. By selecting our developer select we simply attach an event and pass in the name of the function we would like to call when the event occurs.



Now we can write our method that handles the actual logic of our application. Remember all that code we wrote earlier, it was ugly right? This to me is a better approach, first you can get the selected option using the option:selected selector. This will return to us a jQuery object and we can get what we need by using the val() and text() attributes. The html() method in this case sets the contents of an element.


There is a link below for a live demo of this. This was just a quick example of why I enjoy using jQuery. The code is clean and I am never guessing what some method returned to me (object/string/date) because I will almost always get back a jQuery object. If you have any questions about this example let me know and for you more advanced users I got some good stuff in the pipe so stay tuned.

Select Demo

Categories: JavaScript,jQuery

About The Author

My name is Dan Vega and I am a Software Developer based out of Cleveland OH. I love to play with new technologies and write about my experiences here. When I am not busy being a full time geek I love to lift heavy weights and hang out with friends and family. If you have any questions please don't hesitate to contact me.

Follow me on:
  • Daniel Kim

    I’ve got much love for the jQuery. I’m definitely looking forward to your future posts.

    It’s amazing how succinct jQuery allows client side code to be. Not as clear as your example (the following is probably more terse than succinct), but it’s amazing that this kind of code can be written with such brevity with jQuery:

    $(function(){
    $("#developer").change(function() {
    $("#output").text( this.value != 0 ? "You Selected " + $(this).find(":selected").text() : ” );
    });
    });

  • http://www.coldfusionjedi.com Raymond Camden

    Are you sure you need to use id:selected? When I do

    $("##issuetype_filter").val()

    It returns the value. I don’t have to get the selected property at all.

  • http://therealdanvega.com Dan Vega

    That works and gives me the value but try getting the text().

  • http://www.coldfusionjedi.com Raymond Camden

    I think I see it. val() works fine on the item itself. text() though only works with selected:

    console.log($("#foo").val());
    console.log($("#foo option:selected").text());

    In most cases folks will just want the val though and not needing to specify selected will make the code a bit slimmer.

  • http://www.coldfusionjedi.com Raymond Camden

    What I love is that if you do val() on a multi select, you get a nice list of values back. That kicks butt. It seems like val() just plain works no matter what the form field type is.

  • http://therealdanvega.com Dan Vega

    I did not know you could do that with a multi select, nice tip!

  • http://www.swartzfager.org/blog Brian Swartzfager

    Sometimes you want both the value and the text of the selected item. I have a page where students select their mentors from a drop-down list, and I use the text of the option to add the mentor to an unordered list of mentors already associated with the student and the value of the option in the AJAX call that adds the student-mentor relationship to the database.

    I also use a jQuery plugin on that same page that lets you easily add, remove, and sort the options in a select box (http://www.texotela.co.uk/code/jquery/select/). So when the student selects a mentor from the select box, that option is removed, and when the student clicks on a mentor in their existing list of mentors, an option for that mentor is added to the select box and the options are re-sorted so that the mentors remain in alphabetical order (and the AJAX calls work behind the scenes to keep the database up-to-date).

  • http://cfsilence.com todd sharp

    I’m not an expert, but I’d avoid declaring a local variable (output) that has the same name as a DOM element. I may just be anal, but I’ve seen IE choke on things like that in the past. I could be dead wrong though…

  • http://therealdanvega.com Dan Vega

    @Brian – Great stuff! Some plugins such as the one you mentioned are really great. I like them to be able to dive into the source and find out how easy things in jQuery get easier.

    @Todd – You would think that declaring the variable private would make it safe but I will stay on the look out.

  • http://www.bennadel.com Ben Nadel

    @Ray,

    I didn’t know that about the multi-select either. Very cool! jQuery val() is sweeet.

  • http://cfsilence.com todd sharp

    @Dan – You would think IE followed standards too…..

    Kidding (kinda) – but as I said it may be just me being anal but I avoid that kind of thing…

  • http://cfsilence.com todd sharp

    And what wonderful timing… while it may not be exactly the same issue, this is the kinda thing I’m talkin about —> http://www.coldfusionjedi.com/index.cfm/2008/7/1/IE-issue-with-AjaxProxy

  • http://www.xerrano.com Felipe Serrano

    Does any one know how to create two related cfselects with (this sample) jQuery. Every cfselect is populated from two functions in a CFC (each function is cfquery)

    Thanks guys

  • http://therealdanvega.com Dan Vega

    I just did it the other day and planned on showing it off as 1 of my demos. I will move it up the priority list and try to post something tonight.

  • http://www.xerrano.com Felipe Serrano

    I finally got it working:

    Using:
    http://www.msxhost.com/jquery/linked-selects/json/

    JSCallingFunction:
    $(‘#firstselect’).linkedSelect(‘/cfcs/qryComponent.cfc?method=methodName’,’#secondselect’,{firstOption: ‘Search all’});

    Note: "str" is passed automatically

    CFFunction (CF8):
    <cffunction name="methodName" access="remote" returnformat="json" returntype="array" output="false">
    <cfargument name="str" default="">

    <cfquery datasource="#application.dsn#" name="qryname" >
    SELECT *
    FROM table
    WHERE ID = ‘#arguments.str#’
    </cfquery>

    <cfscript>cfcstruct = ArrayNew(1);</cfscript>

    <cfloop query="qryname">
    <cfscript>
    cfcstruct[currentRow][‘optionValue’] = val_id;
    cfcstruct[currentRow][‘optionDisplay’] = val_text;
    </cfscript>
    </cfloop>

    <cfreturn cfcstruct>
    </cffunction>

    Thanks guys!

  • http://therealdanvega.com Dan Vega

    Glad to see you got it working and thanks for the link. I ended up doing it manually but this looks a lot easier and that is always the goal!

  • Brad

    So I’m trying to grab the selected value from a dropdown list in a jqgrid.
    The dropdown is populated dynamically when the user changes another value in the jqgrid.

    I can’t get the selected value is the issue.

    I can get the desired cell with the html using html(). (<SELECT name=subJList Enabled="true"><OPTION selected>Main</OPTION><OPTION>Support</OPTION><OPTION>Support Management</OPTION><OPTION>Development</OPTION><OPTION>Co-Op Development</OPTION></SELECT>)

    I’ve tried to create a new element and set the above code as the html then retreive the selected value.

    Using .text() returns all the values in the dropdown.

    i’m out of ideas except to parse the string but I assumed there’s a better way.

    Thanks

  • http://therealdanvega.com Dan Vega

    Brad – Do you have this up somewhere that I could look at? When an option is selected in my example I am listening for a change event. This will tell me that a new value is selected. Using that we can grab the selected value using $("#developer option:selected").val()

  • Michael Everitt

    Very nice explanation, thanks!

  • Daniel

    This one is pretty easy, in fact, easier without jquery.

    <select onchange="if(this.options[selectedIndex].text!=’Select 1′)document.getElementById(‘textbox’).innerHTML=this.options[selectedIndex].text;" >
    <option>Select 1</option>
    <option>test1</option>
    <option>test2</option>
    <option>test3</option>
    </select>
    <div id="textbox">

    </div>

  • http://therealdanvega.com Dan Vega

    To me that it is not an easier solution. The code just does not look clean to me. That is why love the jQuery approach. It is very simple clean and right when you look at it you know whats going on.

  • Daniel

    Got to make one more attempt. This one would work very well if you need to use the function multiple times with multiple elements.

    If the selected option’s text does not equal the first selection it does not change the text, otherwise it will change the text for whatever you specify when calling the function.

    <html>
    <head>
    <script type="text/javascript">
    function selectchange(x,y)
    {
    if(x.options[x.selectedIndex].text!=x.options[‘0′].text)document.getElementById(y).innerHTML=x.options[x.selectedIndex].text;
    }
    </script>
    </head>
    <body>
    <select id="selected" onchange="selectchange(this,’textbox’);">
    <option>Select 1</option>
    <option>test1</option>
    <option>test2</option>
    <option>test3</option>
    </select>
    <div name="textbox" id="textbox">
    </div>
    </body>
    </html>

  • russell

    thanks!

  • Chris

    If you’re after an API for common form field tasks, this plugin provides extra methods:

    http://code.google.com/p/jquery-form-extensions/

    It has methods such as (plus many more):
    – isRadioBox
    – isChecked
    – isSelected
    – selectedValue
    – selectedValues()

    e.g. $("#myradio").selectedValue() would find the selected value from all the radio options.

  • http://therealdanvega.com Dan Vega

    @Chris – Thanks for the links, looks interesting!

  • http://brianseagraves.com Brian Seagraves

    Thanks, Somehow I misses rhe change function; was trying to use a combo of blur and focus

  • http://lanzwebdesign.com/ John Lanz

    Thanks brad,
    I’ve been looking this selector all day long:
    var selected = $("#developer option:selected");

  • http://profissionais.ws Maicon

    good, but I have another ask,
    how to chage the selected item using jquery?

  • stexas

    thanks thanks for your post. great help

  • http://naafsvandijk.nl Sebastiaan

    Hi Dan, all over CF-sites I can find chained select snippets and code, but no related selects. By that I mean two selectboxes on either side with four controls in the middle. The controls let you push/pull elements from one select to the other and vice versa. Have you any idea where I can find example code for that? Or a jquery tutorial. Preferably a snippet which will allow me to use these several times on the same page without the JS being screwed… :-)

  • http://www.semseo.co.uk Chris

    @ Sebastiaan

    Maybe this?
    http://selectswap.riaforge.org/

  • http://onlinebase.nl/ Sebastiaan

    @Chris: Thanx for the tip, it looks like a very alpha version piece of software, but I’ll give it a go, see if it’s good enough for a production version of our webstore.

  • http://www.silicus.com Silicus

    Is there good looking dropdown jQuery box where we can have icons next to each items? Or even show hierarchy within the items.

  • http://therealdanvega.com Dan Vega

    Can you give me a better idea of what your trying to do?

  • http://onlinebase.nl/ Sebastiaan

    @Silicus: Hierarchy can be accomplished using OPTGROUP within a selectbox. You can create a whole tree-structure with that ;-)

  • Kranti

    HI… this code is realy helpful… n helped me to solve my problem in selecting data from dropdown list using jQuery… thanks …

  • http://elainevellacatalano.com Elaine

    This was just what I was looking for! Thanks, really helpful :)

  • http://www.chooseachat.com Shelton

    hi,

    this is exactly what i’m looking for, but as i’m a complete newbie to jquery, or js in general i’m stuck…

    i need to render the output into a hidden value, because i want to send the selected option into paypal as the product title…. and obviously when i stick my code into value="" then it messes up…

    anyone able to help me out? :-\

    thanks alot

    Shelton

    p.s. the XX’s are where i need it to render:
    <input type="hidden" name="item_name" value="XX Orders to MyCOMPANY">

  • dujovski

    I find this post very useful. But when i want to use on jQueryMobile website nothing happens. Can you help me?

  • http://www.e-zest.net/ Mike Bosch

    I was searching for this and found this article which is helped me. Thanks Dan.

  • Chris

    Excellent post. It helped to solve my problem.
    Thank you for sharing.

  • Gordon

    any help why

    alert($(this).find(":selected").attr("selectedIndex"));

    yielding "undefined"?

  • Gordon

    While

    $(this).find(":selected").attr("selectedIndex");

    comes up undefined, jQuery this object as DOM object works:

    $("#tblUAssgn select[id^=’selMain’]").change(function(){
    alert(this.selectedIndex);
    });

  • http://goldpricetoday.ws johnny

    oh, great. I help me a lot. Thanks!!!

  • http://astaza.com/ games

    hello thanks for this code but i need to select a option using jquery and value
    thank you

  • Lyuba

    Thanks a lot