0

I'm new on javascript and jquery. The problem is that: when i select an image, it does not appear immediatly in preview. I solved this partially with this piece of code:

document.getElementById("id_shield_image").onchange = function () {
            var reader = new FileReader();

            reader.onload = function (e) {
                if($("#parameters_edit_form img").length != 0){

                    $("#parameters_edit_form img").attr('src', e.target.result);
                }
            };

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

Now, the image appear only if there was another image befere, but if I do this for the first time, it doesn't work.

Here is the HTML of the form:

<div id="main-content" class="col-12">
    <div class="row">
        <div class="col-12">
            <form id="parameters_edit_form" enctype="multipart/form-data" method="POST">
                {% csrf_token %}
                {% bootstrap_form %}
            </form>
        </div>
    </div>
</div>

Can anyone help? Thanks in advance!

1 Answers1

1

At a guess based on the limited HTML shared, you need to create the element when its not on the page.

document.getElementById("id_shield_image").onchange = function () {
            var reader = new FileReader();

            reader.onload = function (e) {
                if($("#parameters_edit_form img").length != 0){

                    $("#parameters_edit_form img").attr('src', e.target.result);
                }else{
                    var img = $('<img>');
                    img.attr('src', e.target.result);
                    img.appendTo('#parameters_edit_form');
                }
            };

            reader.readAsDataURL(this.files[0]);
        };
Squiggs.
  • 4,299
  • 6
  • 49
  • 89