Nate Pet
Nate Pet

Reputation: 46222

Pass input parameter to .click event

I have a function as follows:

      $("#submitBtn").on('click', function () {
          ....
      });

I am using the following in invoke the click it in a portion of code by doing:

     $('#submitBtn').click();

Is there a way to set a input parameter to the click. For example, I need to pass a string value to the click so that the function can take appropriate steps. Note that the value of p is not from any element from the page. It is something I will be pro-grammatically setting based on some conditions.

     var p = 'sourceinfo';

     $('#submitBtn').click(p);

Upvotes: 2

Views: 1792

Answers (5)

htmler
htmler

Reputation: 380

Alright, the best way to do this is by adding custom data-attribute params to the element before chaining it with the click event:

$("#submitBtn").data("params", {
    one: "Parameter 1",
    two: "Parameter 2"
}).click();

And you can use params like this:

$("#submitBtn").on('click', function () {

    // Parameter 1
    alert( $(this).data("params").one );

    // Parameter 2
    alert( $(this).data("params").two );

    // Do other stuff

});

Check working demo

Upvotes: 1

Shir Gans
Shir Gans

Reputation: 2027

You can you jQuery(this).attr('action') ... Inside the function And on the element add attribute as follow data-action('myaction')

Upvotes: 0

Ahmad ikram
Ahmad ikram

Reputation: 140

You can use .trigger() instead.

$('#submitBtn').trigger('click', [arg1, ...]);

You can retrieve the parameters passed when attaching the click handler

$('#submitBtn').on('click', function(e, arg1, ...) {
});

Upvotes: 0

Hizem
Hizem

Reputation: 181

You can use the event handler .trigger() instead of .click() Syntax :

.trigger( eventType [, extraParameters ] )

Example:

.trigger('click',[param1,param2]) 

After that you can get those params from your call back function after event param

Upvotes: 0

jayachandran m
jayachandran m

Reputation: 9

Click is a event generated and cannot pass the message/data. Instead you can pass the args to the listener(calling method).so that it can be captured to that method. for e.g

<button onclick="handleClick('msg',event)"></button>

Upvotes: 0

Related Questions