Select multiple images in a loop and display them individually with jQuery

Viewed 752

I have loop buttons to select the image:

            @foreach (var item in image)
            {
                <label class="control-label col-md-7 ">
                   select image
                </label>
                <img id="imgworksample" src="~/site/imgworksample/@item.imageName" class="img- 
                 thumbnail" />
                <input type="hidden" value="@item.ImageId" />
                <input id="img_worksampleupload" name="imgpostupload" type="file" />
                <hr />
            }

I want the button browser inside the loop to be clicked Select an image and display it?

How to do with jQuery?

this work for one browser button:

 <script>
    function readURL(input) {

        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('#imgworksample').attr('src', e.target.result);
            }

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

    $("#img_worksampleupload").change(function () {
        readURL(this);
    });
</script>
1 Answers

I want the button browser inside the loop to be clicked Select an image and display it?

Please note that you put your html elements in a loop statement, which would cause the value of the id attribute not unique within your current HTML document.

If you'd like to display/preview the selected image in page, you can try to modify the code like below.

@foreach (var item in image)
{
    <label class="control-label col-md-7 ">
        select image
    </label>
    <img src="~/site/imgworksample/@item.imageName" class="imgworksample img-
                 thumbnail" />
    <input type="hidden" value="@item.ImageId" />
    <input class="img_worksampleupload" name="imgpostupload" type="file"/>
    <hr />
} 

jQuery code

<script>
     function readURL(input, imgcontainer) {

        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $(imgcontainer).attr('src', e.target.result);
            }

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

    $(".img_worksampleupload").change(function () {
        
        //find target image container and pass it as parameter to custom function
        var target_imgtag = $(this).prev().prev();

        readURL(this, target_imgtag);
    });
</script>

Test Result

enter image description here

Related