Replace input file with icon/image with Image Preview

Asked

Viewed 358 times

0

I have a form where it has a input file with preview image before upload, trying to replace the input for an image, but I’m not getting it.

PREVIEW SCRIPT Como está ficando!!!

<script>
    // PREVIEW FOTO
    function PreviewImage() {
        var oFReader = new FileReader();
        oFReader.readAsDataURL(document.getElementById("uploadImage").files[0]);

        oFReader.onload = function (oFREvent) {
            document.getElementById("uploadPreview").src = oFREvent.target.result;
        };
    };
</script>

HTML

<div class="image-upload"><label for="file-input">
                                        <img src="https://i.pinimg.com/originals/54/38/19/543819d33dfcfe997f6c92171179e4cd.png" id="uploadPreview" style="width: 110px; height: 110px;" />  
                                        <input id="uploadImage" id="file-input" type="file" name="foto" onchange="PreviewImage();" />   

CSS

 <style type="text/css">
    .image-upload > input
    {
    display: none;
    }
    </style>

Someone help me, I thank you in advance.

1 answer

1


First off, your tag div was not closed properly, so the css applied in the class image-upload was not applied and the file select button was still in evidence.

Second, the attribute of for tag label must have the same value as the attribute id of your tag input. In your code, the tag input had two attributes id.

Changing your HTML to the example below will work correctly.

<div class="image-upload">
        <label for="uploadImage">
            <img src="https://i.pinimg.com/originals/54/38/19/543819d33dfcfe997f6c92171179e4cd.png" id="uploadPreview" style="width: 110px; height: 110px;">
        </label>  
        <input id="uploadImage" type="file" name="foto" onchange="PreviewImage();">
    </div>
  • Thank you, it worked! A little question, there is no way to get the comic next to where the picture appeared then?

  • 1

    Yes, remove CSS . image-upload > input { display: None;} and then the Select Image button will be next to the preview image.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.