jQuery – Pass a different field object during the bind function

jQuery often uses bind to handle field events. The field itself is passed on to the calling function and can be referenced via the popular “this” keyword. But in case you need to pass on another field object to the function, you can easily do so. But it took me a little time to figure out how that object is retrieved within the calling function. Here’s a small snippet to demonstrate the jQuery behavior.



$(document).ready(function(){
  $( "#id_button" ).bind("click", $( "#id_region" ), btnClick);
)};

var btnClick = function(e) {
  $btnFld = $( this );
  $passedFld = e.data;
  alert($btnFld.val()); //Will output "Click"
  alert($passFld.val()); //Will output "US-EAST"
};

HTML simulation
===============
SELECT id="id_region"
OPTION "US-EAST" selected="selected"
OPTION "US-West"
OPTION "Europe"
OPTION "Singapore"
/SELECT

input type="button" id="id_button" value="Click"

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s