For multiple uploaders, you need to set the click function on class and not on ID. Try the following (note the declaration of the parent element as variable):
jQuery(document).ready(function($){
var custom_uploader;
var parent;
$("input[class^='upload_image_button']").click(function(e) {
parent = $(this).closest('table'); // OR WHATEVER ELEMENT IS THE CLOSEST PARENT TO THE UPLOADER AND THE TEXT INPUT FIELD
e.preventDefault();
//If the uploader object has already been created, reopen the dialog
if (custom_uploader) {
custom_uploader.open();
return;
}
var myClass = $(this).attr("class");
var field = "#upload_image_"+myClass;
alert(myClass);
//Extend the wp.media object
custom_uploader = 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
custom_uploader.on('select', function() {
var parent2 = parent;
attachment = custom_uploader.state().get('selection').first().toJSON();
parent2.find(field).val(attachment.url);
});
//Open the uploader dialog
custom_uploader.open();
});
});
I’ll try this ASAP. thanks.
This is what I did to get the project off the road block. It still requires manual tweaking but adding something to an array was easier than duplicating large amounts of text.
Thanks again.
jQuery(document).ready(function($){
var custom_uploader;
var image_uploaders = new Array (
"img1",
"img2",
"img3",
);
image_uploaders.forEach(function(obj) {
$('#upload_image_button_'+obj).click(function(e) {
e.preventDefault();
custom_uploader = wp.media.frames.file_frame = wp.media({
title: 'Choose Image',
button: {
text: 'Choose Image'
},
multiple: false
});
custom_uploader.on('select', function() {
attachment = custom_uploader.state().get('selection').first().toJSON();
$('#upload_image_'+obj).val(attachment.url);
});
custom_uploader.open();
}); // end image uploader
}); //end foreach
});
Hello mate. You saved my day. This code worked for me. The line
jQuery(“input[class^=’upload-quote’]”).click(function(e) {} did the trick for me. Maybe useful for others that are looking for the same thing. Here is my code.
jQuery(document).ready(function($){
var custom_uploader;
var row_id
jQuery("input[class^='upload-quote']").click(function(e) {
e.preventDefault();
row_id = jQuery(this).attr('id');
//If the uploader object has already been created, reopen the dialog
if (custom_uploader) {
custom_uploader.open();
return;
}
//Extend the wp.media object
custom_uploader = wp.media.frames.file_frame = wp.media({
title: 'Choose Quote',
button: {
text: 'Choose Quote'
},
multiple: false
});
//When a file is selected, grab the URL and set it as the text field's value
custom_uploader.on('select', function() {
alert( row_id);
attachment = custom_uploader.state().get('selection').first().toJSON();
jQuery('#' + row_id).val(attachment.url);
});
//Open the uploader dialog
custom_uploader.open();
});
});