0

Hi in the below code I am going to upload the image using following java script function.for the first input working fine.In the same way how to call second input field when I am passing the id it's got changes the first one and second one images are displaying same.

html

 <div class="person_pic">
    <label>Please upload your photo</label><input  type='file' name="image" onchange="readURL(this);" />
    <img id="blah" src="#" alt="your image" />
</div>
<div class="person_pic">
    <label>Please upload your family photo</label>
    <input  type='file' name="image" onchange="readURL(this);" />
    <img id="blah1" src="#" alt="your image" />
</div>

javascript

function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {
            $('#blah')
                .attr('src', e.target.result)
                .width(150)
                .height(200);
        };
        reader.readAsDataURL(input.files[0]);        
    }
    if (input.files && input.files[0]) {
        var reader = new FileReader();    
        reader.onload = function (e) {
            $('#blah1')
                .attr('src', e.target.result)
                .width(150)
                .height(200);
        };
        reader.readAsDataURL(input.files[0]);                    
    }
}
Emre Türkiş
  • 992
  • 9
  • 23
hsp care
  • 117
  • 1
  • 2
  • 12

1 Answers1

1

You can try passing the id of the img element that you want to change.As you are using $('#blah') for both the function call , hence both the time same image is being displayed.You can do this:

<script>
        function readURL(input,x) {
            if (input.files && input.files[0]) {
                var reader = new FileReader();
                x = '#'+x;
                reader.onload = function (e) {
                    $(x)
                        .attr('src', e.target.result)
                        .width(150)
                        .height(200);
                };
                reader.readAsDataURL(input.files[0]);
            }
        }
</script>
<div class="person_pic">
    <label>Please upload your photo</label>
    <input  type='file' name="image" onchange="readURL(this,'blah');" />
    <img id="blah" src="#" alt="your image" />
</div>
<div class="person_pic">
    <label>Please upload your family photo</label>
    <input  type='file' name="image" onchange="readURL(this,'blah1');" />
    <img id="blah1" src="#" alt="your image" />
</div>
avinash pandey
  • 1,321
  • 2
  • 11
  • 15