jQuery Select Example

Tags: Ajax,jQuery
Word Count: 1152

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

Comments

#1 Posted By: Daniel Kim Posted On: 7/1/08 6:19 AM
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() : '' );
});
});
#2 Posted By: Raymond Camden Posted On: 7/1/08 7:30 AM
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.
#3 Posted By: Dan Vega Posted On: 7/1/08 7:40 AM |
Author Comment
That works and gives me the value but try getting the text().
#4 Posted By: Raymond Camden Posted On: 7/1/08 7:41 AM
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.
#5 Posted By: Raymond Camden Posted On: 7/1/08 8:16 AM
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.
#6 Posted By: Dan Vega Posted On: 7/1/08 8:20 AM |
Author Comment
I did not know you could do that with a multi select, nice tip!
#7 Posted By: Brian Swartzfager Posted On: 7/1/08 8:22 AM
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).
#8 Posted By: todd sharp Posted On: 7/1/08 9:16 AM
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...
#9 Posted By: Dan Vega Posted On: 7/1/08 9:21 AM |
Author Comment
@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.
#10 Posted By: Ben Nadel Posted On: 7/1/08 10:17 AM
@Ray,

I didn't know that about the multi-select either. Very cool! jQuery val() is sweeet.
#11 Posted By: todd sharp Posted On: 7/1/08 11:14 AM
@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...
#12 Posted By: todd sharp Posted On: 7/1/08 11:17 AM
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/I...
#13 Posted By: Felipe Serrano Posted On: 7/2/08 4:34 PM
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
#14 Posted By: Dan Vega Posted On: 7/2/08 4:36 PM |
Author Comment
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.
#15 Posted By: Felipe Serrano Posted On: 7/3/08 2:42 AM
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!
#16 Posted By: Dan Vega Posted On: 7/3/08 1:42 PM |
Author Comment
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!
#17 Posted By: Brad Posted On: 7/10/08 2:18 PM
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
#18 Posted By: Dan Vega Posted On: 7/10/08 2:25 PM |
Author Comment
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()
#19 Posted By: Michael Everitt Posted On: 12/12/08 8:34 PM
Very nice explanation, thanks!
#20 Posted By: Daniel Posted On: 12/29/08 8:49 PM
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>
#21 Posted By: Daniel Posted On: 12/30/08 2:46 AM
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>
#22 Posted By: Dan Vega Posted On: 12/30/08 7:19 AM |
Author Comment
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.


Post Your Comment







Show Captcha

If you subscribe, any new posts to this thread will be sent to your email address.

Copyright © 2007 Dan Vega | BlogCFC was created by Raymond Camden. This blog is running version 5.8.001.