Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

In my theme option page, I have 5 image upload boxes.

The jQuery code for loading the wordpress image upload window on button click is:

jQuery(document).ready(function($){
var custom_uploader;
$('#setting-form').on("click", ".upload_button", function(e) {
    var id = $(this).attr('class').split(' ')[1];
    if (custom_uploader) {
        custom_uploader.open();
        return;
    }
    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();
        alert(attachment.url);
        alert(id);
        $("." + id + "_url").val(attachment.url);  
    });
    custom_uploader.open();
});

});

The problem is with this 'line':

custom_uploader.on('select', function() {
    attachment = custom_uploader.state().get('selection').first().toJSON();
    alert(attachment.url);
    alert(id);
    $("." + id + "_url").val(attachment.url);  
});

What happens is that id gets set once, and then it doesn't change, which means the url always gets inserted into the same place which is the first id that was clicked. If I try to alert() the id outside of this .on() line, it changes accordingly.

What could be wrong?

share|improve this question
    
Can you provide the generated HTMl markup here, and does the number of inputs are dynamic or fixed? If fixed you can easily provide a seperate id for each and then get their id as var div_id = jQuery(this).attr('id'); –  sven Jul 18 '13 at 13:27
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.