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]);                    
    }
}
2

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

1 Comment

this answer only I am looking

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.