-1

I have a upload part where I would like to upload an image. But I don't want to use the standard upload button, therefore I have the label with an image.

HTML

  <div class="image-upload">
    <label for="imgInp"><img id="blah" src="https://www.gravatar.com/avatar/9a6676e137fefad07752853bcc656a39?s=48&d=identicon&r=PG&f=1" width="320px" height="240" style="padding-bottom:10px" /></label>
    <input type='file' id="imgInp" />
  </div>

Script

function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('#blah').attr('src', e.target.result);
        }

        reader.readAsDataURL(input.files[0]);
    }
}

$("#imgInp").change(function(){
    readURL(this);
});

css to hide the default upload button

.image-upload > input {
  display: none;
}

What I would like to do is change the image src-url inside a label tag. What is a clever way to achieve this? I've tried something like up, but when I enclose the image preview with a label, the code does not work anymore.

1 Answers1

0

There's just a little typo. You've used

$('#blah').attr('src', e.target.result);

but your image element's ID is blahh

obscure
  • 11,916
  • 2
  • 17
  • 36
  • Try changing the way you're attaching the change event listener to `$(document).on('change', '#blah', function() { });` as outlined by Mark Schultheiss here: https://stackoverflow.com/a/9929631/6504633 – obscure Apr 14 '19 at 09:41