0

I have followed the following link and implemented the example for my own script.

Preview an image before it is uploaded

I have 8 file upload inputs followed by a img tag of it's own

<input type="file" name="file[]" accept="image/gif,image/jpeg" onchange="readURL(this,1);"/>
<img id="imagediv1" src="#" alt="your image" />

Now the javascript I modified

function readURL(input,cnum) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            var cimage = 'imagediv'+cnum;
            reader.onload = function (e) {
                $("#cimage")
                    .attr('src', e.target.result)
                    .width(150)
                    .height(200);
            };

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

I did an alert(); within the javascript and the cimage var does get created properly. However, the img doesn't change as it does in the example. I did try manually creating a function for each imagediv#, and it works fine.

Am I missing something within the javascript ?

2 Answers 2

1

You need to take "cimage" out of the quotes and instead concatenate it to "#":

$("#"+cimage)

Or, better yet, don't bother with creating the cimage variable at all and just do this:

$("#imagediv" + cnum)
Sign up to request clarification or add additional context in comments.

Comments

0

Change your selector:

$("#" + cimage).attr("src", e.target.result).width(150).height(200);

Your selector $("#cimage") is looking for an element with id="cimage".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.