views:

51

answers:

3

I'm trying to pass an element's id to storePair

$("#someid").click(storePair($(this).val(),$(this).attr("id"));

using $(this) doesn't work. no value.

Another stackoverflow post suggests that I use an anonymous function as a wrapper for StorePair(val,id), i.e.,

$("#someid").click(function(){storePair($(this).val(),$(this).attr("id")});

That seems kind of roundabout... Is there a way to call StorePair and pass the value and id without using the anon function?

A: 

use the event data?

var someId = $("#someid");

someId.bind("click", 
                  { value : someId.val(), id: someId.attr("id") }, 
                  storePair);

but you have access to the element that raised the event inside of storePair through event.target, so you can wrap this in $() and get values inside the function

Russ Cam
Not my downvote, but this won't work, `this` likely refers to `document` or `window`.
Nick Craver
not anymore. Was still editing
Russ Cam
@Russ - Still not quite right, you're getting the value when the click handlers *defined*, not when it's *clicked* :)
Nick Craver
I realise that. I *doubt* you'd be changing the id, but I take the point for the value.
Russ Cam
My downvote; at the time I voted this answer down, its content was only “use the event data” (even without the question mark). Judging from the other comments on this answer, the author should probably think about whether quick-posting and then editing around for three or four times is really the way to go.
Scytale
@Scytale - Welcome to StackOverflow!
Russ Cam
+2  A: 

You can use this inside the storePair function to get what you're after, like this:

function storePair() {
  var val = $(this).val();
  var id = this.id;
  //do stuff
}

Then bind it like this:

$("#someid").click(storePair);

Or, use an anonymous function like you already have, round-about or not, it's the way it works :)

Nick Craver
`this` will only be set to the element being clicked when `storePair` is called via the event handler. If you call it on its own, `this` will refer to the `window` global scope.If you need to support both scenarios, you could accept `id` and `val` as parameters, and then fallback to using `this` if they weren't defined: `val = val || $(this).val();`
bdukes
@bdukes - Yes good point, *if* using this in another context use params and a `||` fallback, I'm unclear from the question whether this is the case or not, but good to note either way.
Nick Craver
+2  A: 

It's not a roundabout, it's supposed to work that way. The click function (and any of the binding function cousins) accept a function object to be evaluated when the event triggers.

You are evaluating the function storePair when defining the callback, so it won't work.

Chubas