0

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

1
  • $('#files').html('<li><img src="upload/'+file+'" alt="" /><br />'+file+'</li>') Commented Jan 15, 2013 at 10:14

1 Answer 1

1

Instead of:

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

Try:

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

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much, I have been working on this for days and now it works, thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.