47

Is there a way to pass data to a change event via jQuery's trigger method?

The issue here is that a click event triggers the upload menu. Once the image is selected, the change event is fired, however. The data I passed into the trigger event's second parameter is passed to the click event, not to the change event. In the example below, data is undefined.

Trigger Image Change

$('.change_main_image').live('click', function() {
    $('input[name=photo].change_uploader').trigger('click', ["some string"]);
});

Event Handler

$('input[name=photo].change_uploader').live('change', function (e, data) {
   alert(data); // undefined
   //canvas resize and upload script
});
2
  • Why not just directly trigger the change event? Commented Nov 22, 2012 at 5:15
  • @TaylorMac can you elaborate? I'm running into this exact same issue and it sounds like it ended up being a non-issue for you. Can you explain what you ended up doing? I need to trigger('click', param) to initiate the upload, but I need param in my change() function. I am getting undefined in the change() function as you indicated in your question. Commented Oct 22, 2019 at 10:23

1 Answer 1

99

.live() is deprecated. Use .on() like this. And change event should be triggered, not click

$('.change_main_image').on('click', function() {
    $('input[name=photo].change_uploader').trigger('change', [{somedata:true}]);
});


$('input[name=photo].change_uploader').on('change', function (e, data) {
   alert(data.somedata); 
   //canvas resize and upload script
});
Sign up to request clarification or add additional context in comments.

3 Comments

And when you need to use .live() because the project was developed in an old version of jquery and your boss tells you that refactoring is not an option... Sad but true.
Why is that when we pass an array from the trigger point, we get the first element of the array instead of the array itself??
this solution still working in 2024. Thanks dear thecodejack :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.