jQuery and wordpress - multiple button function scope

66 Views Asked by At

I am having an issue with scope (I think) on a jQuery function that opens up a media upload window in wordpress.

I have a function which is used on several buttons, but I need to refer to the specific button when returning the result. Have a look at my code:

   var file_frame;

  jQuery('.bjqs_upload_button').live('click', function( event ){

      event.preventDefault();
      current_id = $(this).attr('id');

      [...]


     // When an image is selected, run a callback.

      file_frame.on( 'select', function() {

         attachment = file_frame.state().get('selection').first().toJSON();

         // Set the thumbnail on page to the image just selected

         $("#". current_id).parent().find('img').attr("src", attachment.url);

       });

       ...

  }); 

In the above code I have collected the id of the current button by using the code:

current_id = $(this).attr('id');

Then I have tried to refer to this later in the file_frame.on() function.

$("#". current_id).parent().find('img').attr("src", attachment.url);

I get an 'undefiend' when running an alert on this.

I tried to pass the variable into the function like this

file_frame.on( 'select', function(current_id) {

But the issue remains.

Would love some help on this if possible.

Thanks

1

There are 1 best solutions below

0
On

So I ended up using global variable on this (which i was trying to initially avoid.

Set the variable up

window.current_id = $(this).attr('id');

And called it within the function like so:

$("#" + window.current_id).parent().find('img').attr("src", attachment.url);