I have a question that's basically a follow up to this one: WordPress 3.5 Media Uploader Multiple File Select
I'm using this code to use Wordpress's Media uploader in a plugin admin script that requires three separate text boxes for image uploading. I've edited the code as follows so that it returns the image url into the value of the appropriate text box.
jQuery(document).ready(function() {
var tgm_media_frame;
var field;
var buttonID;
var button;
jQuery('.upload-images').click(function() {
if ( tgm_media_frame ) {
tgm_media_frame.open();
return;
}
buttonID = jQuery(this).attr('id');
button = jQuery("#"+buttonID);
field = button.prev('input');
tgm_media_frame = wp.media.frames.tgm_media_frame = wp.media({
multiple: true,
library: {
type: 'image'
},
});
tgm_media_frame.on('select', function(){
var selection = tgm_media_frame.state().get('selection');
selection.map( function( attachment ) {
attachment = attachment.toJSON();
console.log(field.attr('id'));
field.val(attachment.url);
});
});
tgm_media_frame.open();
});
});
When I click the first button and upoad an image, it works as expected. However, when I click a different button of the same class to upload the next image, the uploader works, but the url is placed in the input field for the first button. Once the field variable is set the first time, it doesn't change. How do I get it to reset after each click so that the URL goes into the appropriate input text field?