I am using this code to insert the image source URL into relevant fields in WordPress's admin panel. This is part of my HTML structure for the form (repeats for every other field in that container) : `
<table>
<tbody>
<tr valign="top">
<th scope="row">
Label for input field 1 :
</th>
<td>
<input class="upload_button" type="button" value="Upload" />
<input type="text" name="upload" class="upload-url" value="Empty"/>
</td>
</tr>
<tr valign="top">
<th scope="row">
</th>
<td class="upload-preview">
<img src="Empty" alt="Preview" />
</td>
</tr>
<tr valign="top">
<th scope="row">
Label for input field 2 :
</th>
<td>
<input class="upload_button" type="button" value="Upload" />
<input type="text" name="upload" class="upload-url" value="Empty"/>
</td>
</tr>
<tr valign="top">
<th scope="row">
</th>
<td class="upload-preview">
<img src="Empty" alt="Preview" />
</td>
</tr>
</tbody>
</table>
This is the Javascript code handling it : `
var image_uploader;
jQuery("div#container").on('click', 'input.upload_button', function(e) {
e.preventDefault();
var formloc = jQuery(this).parent().parent();
//If the uploader object has already been created, reopen the dialog
if (image_uploader) {
image_uploader.open();
return;
}
//Extend the wp.media object
image_uploader = wp.media.frames.file_frame = wp.media({
title: 'Use Image',
button: {
text: 'Use Image'
},
multiple: false
});
//When a file is selected, grab the URL and set it as the text field's value
image_uploader.on('select', function() {
attachment = image_uploader.state().get('selection').first().toJSON();
jQuery(formloc).next('tr').find('img').attr('src', attachment.url);
jQuery(formloc).find('input.upload-url').val(attachment.url);
});
//Open the uploader dialog
image_uploader.open();
});
I am using this structure to keep the form look neat (the preview of uploaded image appears below the input field). When a person has uploaded the image, the image URL should be inserted to the input field, as well as img src to show it immediately.
However, the problem is that this only works on the first click i.e. when I click on Upload Button 1, it works as intended but when I click on Upload button 2, the changes will still be reflected on the area which is supposed to be controlled by Upload Button 1. It seems that $(this) only records the first clicked button and never changes thereafter.
I would really appreciate your help to see what has gone wrong there. I have been cracking my head to find out the problem but to no avail. I'd be ready to provide more info should you need it.
Thanks a lot for helping!
<table>
tag? – Mangesh Parte 58 mins agojQuery(this).parent().parent();
is correct. Billy wants to select onlytr
tag. notform
tag. – Mangesh Parte 57 mins ago<table>
tag now. Thanks guys for checking the code. – Billy 33 mins ago