0

I have a function like below;

function myfunction(param1,param2,param3){
  alert(param1);
  alert(param2);
  alert(param3);
  alert(buttonid);//i want to alert mybutton here
}

$('#mybutton').click(function() {
  myfunction("hi","hello","howdy");
});

The function is evoked using a button click event. I want to alert the button's id in the function called. How can I do this?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Alfred
  • 21,058
  • 61
  • 167
  • 249
  • a possible duplicate of this: http://stackoverflow.com/questions/48239/getting-the-id-of-the-element-that-fired-an-event – Karl Dec 27 '16 at 07:00

2 Answers2

1

The this in your current function is referring to the window object. You want to use the event object (whose target property will refer to the element that triggered the action).

function myfunction(param1,param2,param3){
  alert(param1);
  alert(param2);
  alert(param3);
  alert(event.target.id);
}

Also, I would suggest using the jQuery on listener rather than the click listener. This will make the listener AJAX compatible.

$(document).on("click", "#mybutton", function(){
   myfunction("hi", "hello", "hey"); 
}); 
Lloyd Banks
  • 35,740
  • 58
  • 156
  • 248
  • where does "event.target.id" comes from in your solution? I guess you are missing the "event" parameter in your function? ... function (event) { myfunction("hi", "hello", "hey", event) } – Karl Dec 27 '16 at 07:03
0

Try this

function myfunction(param1,param2,param3,buttonid){
  alert(param1);
  alert(param2);
  alert(param3);
  alert(buttonid);//i want to alert mybutton here
}
$(document).ready(function(){
    $('#mybutton').click(function() {
      myfunction("hi","hello","howdy",$(this).attr('id'));
    });
})