jquery this retain its previous value with the wordpress media library select

i have a button in my WordPress admin to add hotels images.
 when it is clicked it display an upload image link and a hidden text field to take the selected image.
the id of each button is incremented, so on select i can populate the right fields.
 when i click the button the media library does open and i can populate the right field, but only regarding the first selected button, since it retain the first id.
 i realize it is a scope issue, but i cannot make it work.
 the second one i click, is the correct is when on click, but after selection it is the first id. this is my code:
 var mediaUploader;
    $(document.body).on('click','.upload_hotel_image',function(e){
        var that = $(this);
        var thethisid = that[0].id.split('-')[1];

        console.log('outside id: ', thethisid);
    if (mediaUploader) {
  mediaUploader.open();
  return;
    }
    mediaUploader = wp.media.frames.file_frame = wp.media({
  title: 'Choose Image',
  button: {
  text: 'Choose Image'
    }, multiple: false });
    // When a file is selected, grab the URL and set it as the text field's value
mediaUploader.on('select', function() {
        var attachment = mediaUploader.state().get('selection').first().toJSON();
        console.log('inside id: ', thethisid);
});
    mediaUploader.open();
    return false;
    });

Open in new window


now, if i comment the return in the if statement, everything works, but then the media modal does't close. i believe it is a scope issue. i just need the same id in the select part as in the click part.

any suggestions?
LVL 1
derridaAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Julian HansenCommented:
What does your HTML look like.
derridaAuthor Commented:
hey Julian
i have a button that on click append this markup for each hotel:
		var hotelitirator = <?php echo $hotelcount ?> + 1;
		//alert(hotelitirator);
		$(document.body).on('click', '#add-hotel' ,addAnHotel);
		function addAnHotel(){
			$('#hotelslist').append('<hr><p class="form-field pwrapper"><label for="_hotel_name">Hotel Name</label><input type="text" name="_hotel_name[]" value=""></p><p class="form-field pwrapper"><label for="_hotel_url">Hotel URL</label><input type="text" name="_hotel_url[]" value=""></p><p><input role="edit" id="upload_image_button-'+hotelitirator+'" type="button" class="button upload_hotel_image" value="Upload image"/><input id="h-image-'+hotelitirator+'" class="hotel_image-'+hotelitirator+'" type="text" name="hotel_attachment_path[]" value=""><img id="h-preview-'+hotelitirator+'" class="hotel-priview-'+hotelitirator+'" style="width:200px;border:5px solid #FFF" src=""></p><hr>');
			hotelitirator++;
			return false;
		}

Open in new window

i have the same markup when displaying existing hotels. this is why i start with hotelcount + 1.
by the way, if i eneter everything manually, all works, i mean saving so the database and displaying from there. but i need to integrate the wordpress media library. so i added to each append the button with a hidden text field ( right now not hidden) and a preview.
Julian HansenCommented:
You are correct that it is a scoping issue - there is quite a bit going on here. First lets look at why it works when you remove the return statement.

If there is no return each time you click on the Add Hotel it runs the full code - that means it re-binds to the select event - so after two add hotel clicks you have to event handlers bound to select, after 3 adds 3 etc.
In each case the event handler is binding with the value of thethisid at the time the handler was bound.
When you do a select - it runs ALL the event handlers - so one of them is going to work because it was created with the right id.

Now, when you uncomment the return statement - you only ever bind to the 'select' once and you bind to it with whatever value is in thethisid at the time it is bound so it will always be the first click.

To fix this you need to move the declaration of thethisid outside of the click handler - in other words.

var mediaUploader;
// ADD THIS
var thethisid;
$(document.body).on('click','.upload_hotel_image',function(e){
  var that = $(this);
  // DON'T DECLARE HERE
  thethisid = that[0].id.split('-')[1];

  console.log('outside id: ', thethisid);
  if (mediaUploader) {
    mediaUploader.open();
    return;
  }
  mediaUploader = wp.media.frames.file_frame = wp.media({
    title: 'Choose Image',
    button: {
    text: 'Choose Image'
  }, multiple: false });
  // When a file is selected, grab the URL and set it as the text field's value
  mediaUploader.on('select', function() {
    var attachment = mediaUploader.state().get('selection').first().toJSON();
    console.log('inside id: ', thethisid);
  });
  mediaUploader.open();
  return false;
});

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook now!

derridaAuthor Commented:
so as always it works, and i really appriciate the help and details. one question though, where are the buttons to give you the credits?
derridaAuthor Commented:
ok found the button, which should not be an issue to find, may i say.
in any case, great help from Julian
Julian HansenCommented:
Thank you and you are welcome.

PS  The issues of the interface have been noted and they are being addressed.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.