NodeReact020
NodeReact020

Reputation: 506

Javascript - Selected image not being displayed

In my JS file, I check when a user selects a file, and I display this image in the browser. I then allow a user to remove the selected image, and instead an image of a default image is displayed in the browser.

The issue I have is that once a user removes the image by clicking the remove text, they are then unable to select a file they want. This is unexpected.

HTML:

// Label for file input (file input is generated in backend)
<label id="complete-signup-photo-label" for="complete_signup_photo">Choose a profile photo</label>

// Image displayed in browser(should display image user selects from file input above)
<img id="complete-signup-photo-img" width="40px" height="40px" src="{% static 'default-profile.png' %}" alt="">
// User should be able to click, and src of selected file changes to a default image
<span id="complete-signup-remove-photo">Remove</span>

My JS file:

img = $("#complete-signup-photo-img");

// This is my file inputs id (generated in my backend)
$("#complete_signup_photo").change(function(e) {
    var url = URL.createObjectURL(e.target.files[0]);

    img.attr('src', url);
});

$("#complete-signup-remove-photo").click(function(e) {
    img.attr("src", "http://localhost:8000/static/default-profile.png"); 
});

Anybody know why this is happening? Thank you.

Upvotes: 0

Views: 45

Answers (1)

Cagri Tacyildiz
Cagri Tacyildiz

Reputation: 17570

Did u try to initialize file input?

$("#complete-signup-remove-photo").click(function(e) {
    img.attr("src", "http://localhost:8000/static/default-profile.png"); 
    $("#complete_signup_photo").val("");
});

Upvotes: 2

Related Questions