user9030616
user9030616

Reputation: 35

Background on change function for the same parent div

I having a problem to select on change function for within the same parent Div. When the background-image url replace function call, it replace all the background-image url for the class selected. May I know how can I change within the same parent div?

I have try using the .parent and .closest but is not working.

<div class="form-group row">
    <div class="col-md-6">
        <div class="imagePreview"></div>
        <input type="file" class="uploadFile img" value="Upload Photo">
    </div>
    <div class="col-md-6">
        <div class="imagePreview"></div>
        <input type="file" class="uploadFile img" value="Upload Photo">
    </div>
</div>

This is the jquery code I am using

$(function () {
    $(".uploadFile").on("change", function () {
        var files = !!this.files ? this.files : [];
        if (!files.length || !window.FileReader) return;
        if (/^image/.test(files[0].type)) {
           var ReaderObj = new FileReader();
           ReaderObj.readAsDataURL(files[0]);
           ReaderObj.onloadend = function () {
               $(".imagePreview").css("background-image", "url(" + this.result + ")");
           }
        }
    });
});

Upvotes: 0

Views: 54

Answers (3)

Ajju Abdul Ahad
Ajju Abdul Ahad

Reputation: 56

You can also make use of 'prev()' from jquery which will return the immediate previous sibling of that element.

$(function () {
   $(".uploadFile").on("change", function () {

     var $input = $(this);
     var files = !!this.files ? this.files : [];

     if (!files.length || !window.FileReader) return;

        if (/^image/.test(files[0].type)) {
          var ReaderObj = new FileReader();
          ReaderObj.readAsDataURL(files[0]);
          ReaderObj.onloadend = function () {
          $input.prev().css("background-image", "url(" + this.result + ")");
       }
     }
  });
});

Upvotes: 2

Sandeep K.
Sandeep K.

Reputation: 759

Use this line to show image foe specific div.

 $(this).parent().find(".imagePreview").css("background-image", "url(" + this.result + ")");

Upvotes: 1

Deepak Sharma
Deepak Sharma

Reputation: 4170

May be what you can do is - on change call, get the parent of the current .uploadfile, and then in onloadend you can search the .imagePreview inside parent.

Something like -

$(function () {
    $(".uploadFile").on("change", function () {

    var parentDiv = $(this).parent();
    var files = !!this.files ? this.files : [];

    if (!files.length || !window.FileReader) return;

    if (/^image/.test(files[0].type)) {
        var ReaderObj = new FileReader();
        ReaderObj.readAsDataURL(files[0]);
      ReaderObj.onloadend = function () {
          $(parentDiv).find(".imagePreview").css("background-image", "url(" + this.result + ")");
      }
    }
});
});

Try fiddle https://jsfiddle.net/stdeepak22/cy46x7z3/

Upvotes: 0

Related Questions