views:

41

answers:

3

I want to pass few parameters to Click() event in jquery, I tried following but its not working,

commentbtn.click(function(id, name){
    alert(id);
});

And also if we use bind then how we'll do that

commentbtn.bind('click', function(id, name){
    alert(id);
});

Please help!

A: 
var someParam = xxxxxxx;

commentbtn.click(function(){

    alert(someParam );
});
Jakub Konecki
I want to pass them within the event.
Prashant
@Prashant: Can you give an example for that?
Felix Kling
@Prashant - you can't just 'add' more params to your callback! jQuery won't know where to get the values from...
Jakub Konecki
+2  A: 

From where would you get these values? If they're from the button itself, you could just do

commentbtn.click(function() {
   alert(this.id);
});

If they're a variable in the binding scope, you can access them from without

var id = 1;
commentbtn.click(function() {
   alert(id);
});

If they're a variable in the binding scope, that might change before the click is called, you'll need to create a new closure

for(var i = 0; i < 5; i++) {
   $('#button'+i).click((function(id) {
      return function() {
         alert(id);
      };
   }(i)));
}
David Hedlund
+3  A: 

see event.data

commentbtn.bind('click', { id: '12', name: 'Chuck Norris' }, function(event) {
    var data = event.data;
    alert(data.id);
    alert(data.name);
});

If your data is initialized before binding the event, then simply capture those variables in a closure.

// assuming id and name are defined in this scope
commentBtn.click(function() {
    alert(id), alert(name);
});
Anurag
+1 for answering the question that should have been asked.
Noufal Ibrahim