Chomper Stomping
jQuery/JavaScript/CSS 3/HTML 5, Java/PHP/Python/ActionScript, Git, Chrome/Firefox Extensions, Wordpress/Game/iPhone App Development and other random techie tidbits I've collected



Javascript

April 20, 2010

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

jquery-logo

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 is the example

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



About the Author

Christopher McCulloh
E-Commerce developer at Finish Line Co-Author of HTML, XHTML and CSS All-in-one Desk Reference for Dummies Graduated from IU with a Bachelors of Media Arts and Science and a Certificate in Applied Computer Science. Tech Editor for Building Facebook Applications for Dummies and Building Websites All-in-one for Dummies 2nd Edition. Creator and maintainer of the Status-bar Calculator Firefox Extension Three years professional experience in Java E-Commerce Development and four years professional experience with PHP for a combined total of seven years professional JavaScript/HTML/CSS experience




 
 

 
logo

dynode Batch Get Item

Working a lot with node.js, dynode and dynamoDB recently. Still trying to wrap my head around it all. Had a horrible time getting dynode.batchGetItem to work. Here is the error I was getting: { name: 'AmazonError', type: 'Valid...
by Christopher McCulloh
0

 
 
mysqlerror

WP phpBB Bridge: Warning: mysql_set_charset() expects parameter 2 to be resource, boolean given

Warning: mysql_set_charset() expects parameter 2 to be resource, boolean given in wp-content/plugins/wp-phpbb-bridge/inc/widgets/wpbb_topics_widget.php on line 149 This is an error caused by the fact that the WP phpBB Bridge pl...
by Christopher McCulloh
0

 
 
 

Events Calendar Pro Nav Formatting Messed up on Empty Calendar

The Events Calendar Pro (from http://tri.be/) has a few problems. If you are trying to figure out why a calendar with no events in that month has completely screwed up header navigation, just put this line of code inside of tab...
by Christopher McCulloh
5

 

 
warning

OH SHNIKES, WE’VE BEEN HAXORED!!!

Yes. It finally happened. After… 6 years? on the web I finally got hacked. Two domains affected: http://cmcculloh.com http://hallelujahbutton.com (this also of course affected all sub-domains of cmcculloh.com, such as blo...
by Christopher McCulloh
2

 
 
blue-xl

WordPress Settings API – Adding Options to Existing Page

Adding new options to an existing page in the dashboard in wordpress can be maddening. I’ve literally spent 15+ hours dealing with this horrible API at this point. To the point where I wrote two different wrappers for it....
by Christopher McCulloh
0

 




2 Comments


  1. [...] the original post: Using jQuery to bind a function to a select box change and … If you enjoyed this article please consider sharing [...]


  2. You can retrieve the text value of the select box by modifying line 2 to say:

    var selectedValue = $(this).find(“:selected”).text();

    This is useful if you have a select menu like:

    <option value=”234″>An Option</option>

    And you want to retrieve “An Option” instead of “234″.



Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>