Home > Mobile >  How do I pass data into a click() function when manually call it?
How do I pass data into a click() function when manually call it?

Time:11-26

I have two buttons: #btn1 and #btn2. I have set up the following click event handlers:

$('#btn1').click(function(event){
   // do something...
})

$('#btn2').click(function(event){
  $('#btn1').click(); // works
  $('#btn1').click({data:5}); // not firing at all
})

I have Googled but most of the posts are talking about how to display the data when a user really clicks. However, in my case, I am not clicking the #btn1 but just call the click() handler from another function.

Thanks for any help!

CodePudding user response:

use .trigger():

$('#btn1').trigger('click', { data: 5 });

and then the handler should look like:

$('#btn1').click((event, data) => {
  // data should be { data: 5 } here
})

https://api.jquery.com/trigger/

https://jsfiddle.net/hrcnskzm/

  • Related