0

I have a list and for each li record I need to attach image, for this I have a function

The problem is, when I tap i to add img it's opening window and i upload image, then i get URL image and name, this url and name i should have in list.

In this moment the script is adding in-to list, but with duplicating previous values.

JSfiddle

enter image description here

$(document).on("click", ".attach-img", function() {
  $('#imgupload').click();
  $("input[type='file']").on('change', (event) => {
    value = event.target.files[0].name;
    console.log(event.target.files[0].name)

    var imageLink = `<a href="${window.URL.createObjectURL(event.target.files[0])}" target="_blank">${value}</a>`
    $(this).parent().find(".file-name").append(imageLink)
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li>Tets 1 <span class='attach-img'>add img</span>
    <p class='file-name'></p>
  </li>
  <input type='file' id='imgupload' class='hidden' style="display:none">

</ul>
<ul>
  <li>Tets 2 <span class='attach-img'>add img</span>
    <p class='file-name'></p>
  </li>
</ul>
<ul>
  <li>Tets 3 <span class='attach-img'>add img</span>
    <p class='file-name'></p>
  </li>
  <input type='file' id='imgupload' class='hidden' style="display:none">
</ul>
<ul>
  <li>Tets 4 <span class='attach-img'>add img</span>
    <p class='file-name'></p>
  </li>
  <input type='file' id='imgupload' class='hidden' style="display:none">
</ul>
<ul>
  <li>Tets 5 <span class='attach-img'>add img</span>
    <p class='file-name'></p>
  </li>
  <input type='file' id='imgupload' class='hidden' style="display:none">
</ul>
<ul>
  <li>Tets 6 <span class='attach-img'>add img</span>
<p class='file-name'></p></li>
  <input type='file' id='imgupload' class='hidden' style="display:none">
  
</ul>
Andrew
  • 572
  • 6
  • 29

1 Answers1

0

There are many things wrong in here. First of all, id should be unique for every element of the DOM.

Secondly, all of the html elements that are being generated dynamically should follow the same html structure if you want to be able to access them using the same logic.

Moreover, here is the updated fiddle

Fiddle

Muhammad Usman
  • 10,039
  • 22
  • 39