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 ?

Community
  • 1
  • 1
user845009
  • 55
  • 1
  • 6

2 Answers2

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)
gilly3
  • 78,870
  • 23
  • 132
  • 169
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".

Matthew Abbott
  • 57,234
  • 9
  • 99
  • 126