user7152572
user7152572

Reputation: 333

jQuery file upload preview/remove image not working properly

You can find the working file at Jsfiddle

/* JavaScript */

function readURL() {
	var $input = $(this);
    if (this.files && this.files[0]) {
        var reader = new FileReader();
        reader.onload = function(e) { 
            $input.next('.blah').attr('src', e.target.result).show();
            $input.after('<input type="button" class="delbtn" value="remove">');
        }
        reader.readAsDataURL(this.files[0]);
    }
    }

    $(".imgInp").change(readURL); 

    $("form").on('click', '.delbtn', function(e) { 
		var $input = $(this); 
        $input.next('.blah').attr('src', e.target.result).hide();   
        $input.prev('.imgInp').val(""); 
        $(this).closest(".delbtn").remove();    
});
<form name="" action="" method="post">
  <div class="div">
    <input type='file' class="imgInp blah" />
    <img class="blah" src="#" alt="your image"/></div>
  <br>
  <br>
  <div class="div">
    <input type='file' class="imgInp" />
    <img class="blah" src="#" alt="your image"/></div>
</form>

Display and remove image is working fine.

But if the image already selected and again select another new image then preview function is not working. Also remove button keep adding. Please check the error image below.

Click to view the error

Upvotes: 1

Views: 988

Answers (1)

Aruna
Aruna

Reputation: 12022

I have updated your fiddle at following link,

https://jsfiddle.net/balasuar/97dzkf70/20/

When first time you select the image, the next element of the button is the image. But once the image selected, you added theRemove button element next to the file control. So the next time, it breaks as the image is no longer next to the file control.

I fixed it below by having a reset method to clear this.

function readURL() {
    var $input = $(this);
    if (this.files && this.files[0]) {
        var reader = new FileReader();
        reader.onload = function(e) { 
            reset($input.next('.delbtn'), true);
            $input.next('.blah').attr('src', e.target.result).show();
            $input.after('<input type="button" class="delbtn" value="remove">');
        }
        reader.readAsDataURL(this.files[0]);
    }
}

$(".imgInp").change(readURL); 

$("form").on('click', '.delbtn', function(e) { 
        reset($(this));   
});

function reset(elm, prserveFileName){
  if(elm && elm.length > 0) {
    var $input = elm; 
        $input.next('.blah').attr('src', '').hide(); 
        if(!prserveFileName){
          $input.prev('.imgInp').val(""); 
        }
        elm.remove(); 
  }
}

Upvotes: 1

Related Questions