Skip to content
Advertisement

image is not show in img tag when upload it again

I use the following method to upload an image and display it in an img tag. Another button is used to delete that image. Upload and delete are working well, but the problem is when I want to upload an image again after it has been deleted. It does not be show up and when I open the console it did not find the image src. The problem occurs only when I delete the image using the delete button.

 var loadFile = function(event) {
        var image = document.getElementById('output');
        image.src = URL.createObjectURL(event.target.files[0]);
    };

    function deleteFile() {
        var image = document.getElementById('output');
        image.parentNode.removeChild(image);
        var img = document.createElement("img");
        img.id = "output";
        $("#p_img").append(img);
    }


   
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button><label for="file">Upload Image</label </button>
    <button onclick="deleteFile()">Delete</button>
    <p><input type="file" accept="image/*" name="image" id="file" onchange="loadFile(event)" style="display: none;"></p>
     <p id="p_img"><img id="output" height="200" width="200"></p>

Advertisement

Answer

Your file field isn’t triggering the ‘onchange’ event after delete, one way to go about this is to trigger it manually in your delete method.

var loadFile = function(event) {
        var image = document.getElementById('output');
        image.src = URL.createObjectURL(event.target.files[0]);
    };

    function deleteFile() {
        var image = document.getElementById('output');
        image.parentNode.removeChild(image);
        var img = document.createElement("img");
        img.id = "output";
        $('#file').val('');
        $("#p_img").append(img);
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button><label for="file">Upload Image</label </button>
    <button onclick="deleteFile()">Delete</button>
    <p><input type="file" accept="image/*" name="image" id="file" onchange="loadFile(event)" style="display: none;"></p>
     <p id="p_img"><img id="output" height="200" width="200"></p>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement