Passing parameters to click() & bind() event in jQuery?

JavascriptJqueryEvents

Javascript Problem Overview


I want to pass few parameters to click() event in jQuery, I tried following but it's 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);
});

Javascript Solutions


Solution 1 - Javascript

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);
});

Solution 2 - Javascript

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)));
}

Solution 3 - Javascript

var someParam = xxxxxxx;

commentbtn.click(function(){

    alert(someParam );
});

Solution 4 - Javascript

An alternative for the bind() method.

Use the click() method, do something like this:

commentbtn.click({id: 10, name: "João"}, onClickCommentBtn);

function onClickCommentBtn(event)
{
  alert("Id=" + event.data.id + ", Name = " + event.data.name);
}

Or, if you prefer:

commentbtn.click({id: 10, name: "João"},  function (event) {
  alert("Id=" + event.data.id + ", Nome = " + event.data.name);
});

It will show an alert box with the following infos:

Id = 10, Name = João

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondjmzfKnmView Question on Stackoverflow
Solution 1 - JavascriptAnuragView Answer on Stackoverflow
Solution 2 - JavascriptDavid HedlundView Answer on Stackoverflow
Solution 3 - JavascriptJakub KoneckiView Answer on Stackoverflow
Solution 4 - JavascriptHaroldo MacedoView Answer on Stackoverflow