Reputation: 33
I am making a Wordpress widget showing an image, and to upload/change this image I use the Wordpress media uploader.
This is the admin form markup I'm using:
<p class="media-control"
data-title="Choose an image"
data-update-text="Choose image">
<input class="image-url" name="image-url" type="hidden" value="">
<img class="image-preview" src=""><br>
<a class="button" href="#">Pick image</a>
</p>
When I click ".media-control a" the uploader appears and I can pick an image. But when I've picked an image ".image-preview" and ".image-url" isn't updated.
Here's my javascript: http://jsfiddle.net/etzolin/DjADM/
Everything is working as intended except these lines:
jQuery(this).parent().find('.image-url').val(attachment.url);
jQuery(this).parent().find('.image-preview').attr('src', attachment.url);
When I write them like this, input value is set and image preview is updated:
jQuery('.media-control .image-url').val(attachment.url);
jQuery('.media-control .image-preview').attr('src', attachment.url);
But since I use more than one of these widgets it updates the input value and image preview in every widget.
How can I set the input value and update the image preview only in the widget I'm editing? What am I doing wrong?
Upvotes: 3
Views: 18696
Reputation: 318182
Inside the event handler for the media frame this
is not the clicked element
var media_frame;
jQuery('.media-control a').live('click', function (event) {
var self = this;
event.preventDefault();
if (media_frame) {
media_frame.open();
return;
}
media_frame = wp.media.frames.media_frame = wp.media({
title: jQuery(self).parent().data('title'),
button: {
text: jQuery(self).parent().data('update-text'),
},
multiple: false
});
media_frame.on('select', function () {
attachment = media_frame.state().get('selection').first().toJSON();
jQuery(self).parent().find('.image-url').val(attachment.url); // set .image-url value
jQuery(self).parent().find('.image-preview').attr('src', attachment.url); // update .image-preview
// ^^ this is not the element from the click handler but the media frame
});
media_frame.open();
});
and you should be using on()
as live()
is deprecated and removed from jQuery
Upvotes: 3