IsmailS
IsmailS

Reputation: 10863

Pass additional info for event handlers while triggering change event programmatically

$('#idofElement').change(function(e, additionalData) {
  //event code
}

$('#idofElement').trigger('change', { someAdditionalData : 'value' });

I'm triggering a change event from code as you can see above. I want to pass some additional info to event handler. Wanted to know if something like that is possible.

Upvotes: 0

Views: 105

Answers (4)

Matthew Spence
Matthew Spence

Reputation: 1041

You can achieve this by passing a variable with Jquery Trigger, and then opening up your event handler to extra variables. Here is an example:

$("#foo").on("click", function(event, data1, data2) {
  console.log(data1); //logs "hello"
  console.log(data2); //logs "goodbye"
});

$('input:button').click(function() {
  $("#foo").trigger("click", ["hello", "goodbye"]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="foo" type="text" />
<input type="button" value="click me to trigger change event" />

Upvotes: 1

Julien &#39;JS&#39;
Julien &#39;JS&#39;

Reputation: 149

You can store data with data() method like that :

$('#idofElement').trigger('change').data('someAdditionalData', value);

Then you can access to data object like this :

$('#idofElement').on('change', function(){
    if(data = $(this).data('someAdditionnalData')) {
       data...
    }
});

And if you want remove object data, do

$('#idofElement').removeData('someAdditionnalData');

Enjoy :)

Upvotes: 1

Yordan Nikolov
Yordan Nikolov

Reputation: 2678

you can with jQuery.trigger

$(selector).trigger( "click", [ "foo", "bar" ] );

Upvotes: 0

Bharat soni
Bharat soni

Reputation: 2786

// say your selector and click handler looks something like this...

$("some selector").click({param1: "Hello", param2: "World"}, cool_function);

// in your function, just grab the event object and go crazy...
function cool_function(event){
    alert(event.data.param1);
    alert(event.data.param2);
}

Upvotes: 0

Related Questions