Frage

I have a bunch of forms on a page that allow a user to edit information for each respective form. One of the inputs for the form is an image upload.

The forms are of the form below:

<form class="myForm" ...>
    <div class="imagePreview"></div>
    <input type="file" name="myImage" onchange="handleFiles(this.files)" />
</form>

And I have javascript to handle the image preview as follows:

function handleFiles(files) {
    $(".obj").remove();
    for (var i = 0; i < files.length; i++) {
        var file = files[i];
        var imageType = /image.*/;

        if (!file.type.match(imageType)) {
            continue;
        }

        var pic_div = document.getElementById("imagePreview");
        var img = document.createElement("img");
        img.classList.add("obj");
        img.file = file;
        pic_div.appendChild(img);

        var reader = new FileReader();
        reader.onload = (
            function(aImg) { 
                return function(e) { 
                    aImg.src = e.target.result; 
                }; 
            }
        )(img);
        reader.readAsDataURL(file);
    }
}

I want to replace the line:

var pic_div = document.getElementById("imagePreview");

with the appropriate line. This is where I am getting confused. I don't know how to refer to the div of class "imagePreview" for THIS FORM of class myForm.

Any help is much appreciated.

War es hilfreich?

Lösung

The problem is that you're getting the div with the Id imagePreview, when the div in the form have the imagePreview CSS class, what you can do is either give the div the required id, more less like this:

<div id="imagePreview"></div>

Or, if you will have multiple divs with the same class get them using jQuery like this:

$(".imagePreview").each(function(index){
    //Do Something
});

Or:

var pic_div = $(".imagePreview")[0]
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top