21

I am manually calling .click() on a button on a page in my jquery/javascript code.

I need to pass a parameter to click that I can then read on the function that responds to the click event.

is this possible?

Blankman
  • 259,732
  • 324
  • 769
  • 1,199

4 Answers4

37

You need to invoke .trigger(). You can pass over any amount of arguments there.

$('element').trigger('click', [arg1, arg2, ...]);

These extra parameters are then passed into the event handler:

$('element').bind('click', function(event, arg1, arg2, ...) {
}); 

Reference: .trigger()

jAndy
  • 231,737
  • 57
  • 305
  • 359
  • What if event handler already has parameters? Like, I have a button in a grid: - what happens with params if I trigger click event on that button? – FrenkyB Aug 30 '19 at 12:52
1
<button id='test'>

var btn = $("button#test");
btn.attr("param", "my parameter");
btn.click();
Bonshington
  • 3,970
  • 2
  • 25
  • 20
0

No. Your onclick event is separate from your click() function. Normally, this would be possible through arguments[], but in this case you're going to have to use a variable.

0

What kind of argument do you want to pass? I get that these argument are static, since clicking on a button cannot give you any sort of computation.

When you catch the click, you can use this, thus, use it to see what kind of arguments you want to pass

HTML:

<input type="button" id="foo" />

And your JS:

<script>

function iNeedParams(bar, baz) {
  // Computation
}

$("id").click(function() {
  var me = $(this);
  // me contains the object
  // me.attr("id") gives you its ID, then you can call
  iNeedParams("hello", "world");
});
</script>
Jonas Schmid
  • 5,360
  • 6
  • 38
  • 60