Using jQuery to bind a function to a select box change and retrieve the selected value

If you need to bind a function to be called when a user selects an option from a select box using jQuery, you've come to the right place.
There are several different ways to skin this cat, but basically here is what we are going to do:
1. Bind a change event listener to the select box itself
2. When the box is changed, call a function that detects and retrieves the selected value
Here's the code:
$("#selectBoxId").change(function(){
var selectedValue = $(this).find(":selected").val();
console.log("the value you selected: " + selectedValue);
});
Let's break it down line by line.
Line 1:
$("#selectBoxId").change(function(){
$("#selectBoxId") grabs the DOM element out of the html and makes a jQuery object.
.change(function(){}); binds a function to the change event of the select box. Any time anyone changes the selection in the select box this function will fire off
Line 2:
var selectedValue = $(this).find(":selected").val();
var selectedValue creates a new variable that the selected value will be stored in.
$(this) creates a jQuery object based on the select box that triggered the function.
.find(":selected") looks a the select box that triggered the function and finds the option that got selected.
.val() gets the "value" of the selected option.
Line 3:
console.log("the value you selected: " + selectedValue);
this just calls the firebug console in firefox and tells it you want to print something out to it. You don't need this line, but this line shows you that the above code did indeed grab the selected value out of the select box.
Line 4:
});
This just closes the open change function started on line 1.
This code assumes that you have an HTML select box with an id of "selectBoxId". If you have a series of select boxes that all need the same function bound to them for some reason you can give them all the same class name (say "selectBoxesClass") and select them like so: $(".selectBoxesClass").
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Conforming XHTML 1.0 Strict Template</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script type="text/javascript">
$(function(){
$("#selectBoxId").change(function(){
var selectedValue = $(this).find(":selected").val();
console.log("the value you selected: " + selectedValue);
});
});
</script>
</head>
<body>
<select id="selectBoxId">
<option>Foo</option>
<option>Bar</option>
<option selected="selected">Beh</option>
</select>
</body>
</html>
Here are some resources for further reading:
jQuery
jQuery change
jQuery find
jQuery val
jQuery :selected selector
jQuery Element selector
jQuery id selector
jQuery class selector
Firefox
Firebug
Firebug Console
TOTW: Freenode IRC Webchat Client
This week's Tool of the Week is The Freenode IRC Webchat Client.
What it does:
Allows you to chat on Freenode IRC through your browser, even if your corporate proxy blocks IRC (IRC is the third biggest security hole for corporate networks).
When you need it:
- When you don't have an IRC Client installed
- When IRC is blocked
How to use it:
JavaScript Arrays – new Array() vs array literal

Do not every say new Array() when creating a new JavaScript Array(). There are differences between creating an array in Javascript using the array literal, or the fully qualified "object" name (Array() vs []), and the bottom line is that the "right" way to do it is "[]" (array literal) instead of "new Array()". Here is why:
- Most experienced JS programmers use []. [] is the way Douglas Crockford teaches it in JavaScript the Good Parts
(they even talk about it in JavaScript: The Definitive Guide
). Also, if you look in the unminified source for the jQuery library, you will never see Array().
- They appear to be nearly identical, except they aren't.
- [] is more terse and readable, especially for nested arrays:
vs:
- Using the Array() keyword makes you think about arrays as being somehow different from plain vanilla JavaScript Objects (which, yes they are in-so-much as they are Objects with extra methods already defined for you). The literal helps you think about them more object-like because [] looks like {}. Plus, [] is more consistent with the way that you then access the array something[0] so there is less to remember.
- Most importantly, Array() doesn't behave uniformly across argument numbers and types. ((new Array(X)).length === 1 for any X as long as typeof(X) != "number" else Array(X).length === X)
TOTW: Dynamic Dummy Image Generator
This week's Tool of the Week is Dynamic Dummy Image Generator.
What it does:
Allows you to display custom sized dynamic images on any webpage using nothing but a normal image tag and a special URL.
When you need it:
- Mockups
- Prototypes
- Place Holder Images
How to use it:
The Example:
One Click Backup w/ Sabrent & Hitachi
I've been trying to get Mozy backup to work for two months now. First of all, my harddrive is 300GB, and apparently this will take two weeks to backup over my connection. On top of that, there is no "start where you left off" feature, so anytime windows downloads an update and auto-restarts, I'm screwed. So, I can either turn that off, or never have a backup. Crap.
Let's try plan B.
Went to Frye's Electronics and picked up a Sabrent SATA 2.5"/3.5" Hard Drive to USB 2.0 Docking Station, which comes with a one click backup button. Then I grabed a Hitachi Deskstar 500GB Sata HDD. Total cost: $99.00.
End goal is to have two or three HDD, once a week I'll click the button and then grab the drive and toss it in my bag and take it to work and put it in my desk and swap it out with the drive in my desk and bring that one home. Rinse, wash, repeat. The other great thing about the dock is that it is scalable and useful. I can back up as many different computers and as much data as I want. I'm only limited by how many drives I want to buy.
So, a little trouble when trying to get the Hitachi drive to be recognized. I had to right click on "My Computer" and select "Manage". Then I clicked on "Storage" and clicked "Disk Management"; Immediately some dialog thingy popped up asking if I wanted to do such-and-such and I said yes (without snapping a screenshot, oops). This was the end result:
It sees this drive as "drive 5". Cool. Whatever.
So, now I right click on the drive and select something about "format" or "partition" (idk, couldn't get a screen-shot, there's only three options, you'll figure it out) and a dialog pops up. I captured some screen caps of what I did along the way. My choices were based on almost nothing other than gut instinct. We'll see how it works out:

(Selected "no" here because I'm planning on this being assigned dynamically because I'll theoretically be swapping multiple drives out here and I want them all to be seen as the same drive by the computer. So maybe I should have chosen "Z" or something, idk...)
At this point I closed out of the dialog assuming I was done. No Dice. When I went back in I saw it was formatting. After about 15 minutes it was only at 8%:
So, it's going to take a while. About an hour later it's done. Apparently bad call on the not assigning a drive letter. It's ok though, I just right click on the drive partition and select "Change drive letter and path..."
And hey, check it out! There it is!
Now I can easily use the software and one button backup that comes with the sabrent docking station.
This step is going to take a while...
About an hour in...
Went to bed, woke up, and my computer had crashed (it does this at least once a week, another reason Mozy wasn't working). So I checked the backup drive. Nope. Didn't get everything. Got about half of everything. Trying again...
TOTW: Subversion & Subversion Clients for Mac
I did a little research a few months back about Subversion Clients for Mac. I ended up switching to GIT, but since I already had this post mostly finished, here's what I found. This is going to break a little from the traditional TOTW format since it's more of a sampling of a lot of different tools. I've already posted about two of these before...
What it is:
Subversion is a semi-modern version control system. As I said, Git is quickly replacing it as the "next big thing". But if you are going to do version control, and you're not doing Git, you should at least consider Subversion (and I'd stay away from CVS, it's old and borked). It allows you to "save states" of your program. So, instead of "save as" > "myProject1", then "save as" > "myProject1working" and then "myProject1tryNewThing" etc, you would just have one copy of your project/file that you "commit" to your version control. Each commit lives as it's own snapshot so that if you need to go back to another version, you just browse your history and restore that version. You can even "diff" your current version with any other older version to see what you changed if you're trying to figure out how you broke something.
When you need it:
Anytime you do any software project at all, big or small, I'd say you need version control. But here's the bullet list:
Working on a software project:
- In a group
- By yourself on one machine
- By yourself across multiple machines
- Working on an open source project to help distribute the source code
- Joining an open source project (if they don't have version control, they aren't worth joining, unless you are joining to set them up with version control
)
There's a few options out there, but no clear winner. On Windows, TortoiseSVN seems to be the clear winner, and is a great tool. Nothing stands out this way on Mac. At least nothing free. So here you'll find a list of several Subversion clients for Mac. My favorite as of this writing is Versions, but it costs $60 (there's a free 30 day trial). I recommend setting up a subversion server (either on your local machine, or corsair) and using it. Any job worth having is going to require you to use a version control system, so it's best you become familiar with one now.
Here's a question on StackOverflow discussing these plugins if you're interested in learning a little more.
Using Subversion from command line
Martin Ott's Binaries
Free Subversion Book
Versions provides a pleasant way to work with Subversion on your Mac. Whether you're a hardcore Subversion user or new to version control systems, Versions will help streamline your workflow. Versions is here now, so say hello to the fresh new look of your repository and start saying less to that command-line interface. Download the free demo to take it for a spin.
ZigVersion is an easy to use interface for Subversion, a popular open source version control system. Instead of simply reproducing the command line concepts as a graphical interface, we looked at the typical workflows of professional programmers and designed an interface around them.
TOTW: Google Closure JavaScript Compiler Web Interface
This week's Tool of the Week is Google Closure JavaScript Compiler. I know everyone has probably heard of it, but if you haven't gotten around to checking it out, this post is great for you.
What it does:
Allows you to compile JavaScript down to a compressed form. It reads in your JavaScript, parses it, and re-writes it to be much smaller. This is good for you because it will make your site load faster, much faster in some cases.
When you need it:
- To compress your JavaScript
- To combine multiple JavaScript Files
How to use it:
The Example:
Additional Notes:
Notice in the compile directions there is an @output_file_name parameter. You can change this to something other than "default.js" (you can name it anything you want. Then you can actually access the results by clicking on the link on the right hand pane that says "The code may also be accessed at default.js" (if you rename it it will put the name you put instead of default.js). Here's the file generated by my example.
TOTW: Etherpad.com
This week's Tool of the Week is Etherpad.com.
What it does:
Allows you to edit a text file collaboratively in real time with others. Each person's changes are highlighted in a unique color. The file gets saved to their server at a unique URL that you can share and reference. You can view past versions of the file using a "Time Slider". It's kind of like Google Wave, but easier to use... There is even a chat feature on the side of the page for off-document conversation that persists from session to session.
When you need it:
- When walking through or collaborating on some code with another developer
- When collaborating on a text document (like a list or something)
How to use it:
In case you blinked at the end, I had Firefox and Chrome both open and was editing the same pad from within the two browsers. It kept the edits in sync live between the two browsers. This would have been more apparent had I actually had them both showing, which I should have done, but didn't think about it until just now...
TOTW: Firebug HTML > Layout
This week's tool of the week is another component of Firebug, the "Layout" tool.
What it does:
Allows you to edit html element box dimensions directly in the browser to get that perfect witdh/height/padding/margin/border combo you're looking for.
When you need it:
- Resolving float issues
- Adjusting Padding/Margin
- Prototyping Layouts
How to use it:
The example:
Exploring jQuery getScript, or “How I created the jQuery getScriptLite plugin”!
I set out to discover how the getScript function in jQuery works today. Here is what I found. This post sort of illustrates just how easy it is to dig into the jQuery source and really learn the library.
The first thing I did is hop over to github and pop open the source for the 1.3.2 release:
http://github.com/jquery/jquery/tree/1.3.2/src
Since getScript() is an AJAX function, I naturally clicked on "ajax.js". On line 109 I found:
Oh wow! It's just a convenience method! It doesn't do anything magical at ALL. It simply calls $.get().
Now, I could have stopped there, but for fun, let's go deeper. On line 93 I found the get() function:
Ok, so get() is really just a convenience method for ajax(), so let's look for that. Line 25, the ajax() function:
Wait, that's not the one! I don't really know how this works, but that can't be the one because it strips out the script tags. I find another one later on on line 170 that goes all the way to line 451. Way down on line 253 it seems to handle the actual script loading:
Aha! Clever. Creates a script tag and sets it's source to the one we specified and then on line 278 appends it to the head of the document, I'm assuming at that point running the script because two lines later it returns out of the function:
So, there you have it! It would almost seem that you could do the same thing by:
In fact, that seems to work just fine. Hrm... Fork me on github and/or get the plugin!























