1

I have a problem of my jquery code html append :

      html = '<tr id="image-row' + image_row + '">';
      html += '  <td class="text-left image-upload"><a href="" id="thumb-image' + image_row + '"data-toggle="image" class="img-thumbnail"><img src="{{ placeholder }}" alt="" title="" data-placeholder="{{ placeholder }}" /></a><input type="file" class="uploadImage" name="product_image[' + image_row + '][image]" value="" id="input-image' + image_row + '" /></td>';
      html += '  <td class="text-right"><input type="text" name="product_image[' + image_row + '][sort_order]" value="" placeholder="{{ entry_sort_order }}" class="form-control" /></td>';
      html += '  <td class="text-left"><button type="button" onclick="$(\'#image-row' + image_row + '\').remove();" data-toggle="tooltip" title="{{ button_remove }}" class="btn btn-danger"><i class="fa fa-minus-circle"></i></button></td>';
      html += '</tr>';

      $('#images tbody').append(html);

The problem is when append this row and use ON('CLICK', '.class', function(){}) it not working , and i can't get solution of this problem , any help it will be good!

Jquery Function :

    $('.image-upload').on('change', '.uploadImage',function(e){
      console.log('run change img');
      const thisFile = this.files[0];
      var reader = new FileReader();
      var img = $(this).parent().find('img');
      reader.onload = function(e){
        console.log(reader);
        img.attr('src', this.result);
      };
      reader.readAsDataURL(thisFile);
    }); 

1 Answer 1

1

When you use event delegation, the element you bind the handler to has to be a static element, not something that's added dynamically. Since you're adding .image-upload dynamically, you can't bind the delegated event to that. It needs to be a static container element. Since you append these to #images, you should use that.

$('#images').on('change', '.uploadImage',function(e){
  console.log('run change img');
  const thisFile = this.files[0];
  var reader = new FileReader();
  var img = $(this).parent().find('img');
  reader.onload = function(e){
    console.log(reader);
    img.attr('src', this.result);
  };
  reader.readAsDataURL(thisFile);
}); 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, it's working and thank you for explaining the solution

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.