1

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

2
  • I have fixed your issue. Please have a look. Commented Nov 13, 2016 at 11:50
  • @Aruna thanks its working fine :) Commented Nov 13, 2016 at 11:52

1 Answer 1

1

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(); 
  }
}
Sign up to request clarification or add additional context in comments.

Comments

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.