tatty27
tatty27

Reputation: 1554

Replace image in javascript rather than add to list

I have a script that allows the user to upload images and preview them. It's a very basic script and although I have managed to get it to do more or less everything I need I am stuck on one last thing.

As it stands once the user has uploaded an image it is displayed but if they upload another one it displays both, I would like the new image to replace the old image so only one is visible.

I don't have issues with the php side of things, the problem lies in the part where the script appends the new image to list and displays the list rather than just the new image and unfortunately my javascript knowledge is quite limited at the moment.

This is the script:

$(function(){
    var btnUpload=$('#upload');
    var status=$('#status');
    new AjaxUpload(btnUpload, {
        action: 'upload-file.php',
        name: 'uploadfile',
        onSubmit: function(file, ext){
             if (! (ext && /^(jpg|png|jpeg|gif)$/.test(ext))){ 
                // extension is not allowed 
                status.text('Only JPG, PNG or GIF files are allowed');
                return false;
            }
            status.text('Uploading...');
        },
        onComplete: function(file, response){
            //On completion clear the status
            status.text('');
            //Add uploaded file to list
            if(response==="success"){
                $('<li></li>').appendTo('#files').html('<img src="upload/'+file+'" alt="" /><br />'+file);
            } else{
                $('<li></li>').appendTo('#files').text(file);
            }
        }
    });

});

And the images are displayed here:

<ul id="files" ></ul>

Any help will be gratefully received

Upvotes: 0

Views: 75

Answers (1)

David Hellsing
David Hellsing

Reputation: 108480

Instead of:

$('<li></li>').appendTo('#files')

Try:

$('<li></li>').appendTo($('#files').empty())

This will empty the #files element before appending new content.

Upvotes: 1

Related Questions