addCollectionVanilla.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import { autocomplete } from './autocomplete'
  2. (() => {
  3. document
  4. .querySelectorAll('ul.collection-form li')
  5. .forEach(item => {
  6. addDeleteLink(item)
  7. });
  8. document
  9. .querySelectorAll('.add_item_link')
  10. .forEach(btn => {
  11. btn.addEventListener("click", addFormToCollection)
  12. });
  13. function addFormToCollection(e) {
  14. const collectionHolder = document.querySelector('#' + e.currentTarget.dataset.collectionHolderId);
  15. const path = e.currentTarget.dataset.path ?? '';
  16. const item = document.createElement('li');
  17. item.className = collectionHolder.dataset.classLi
  18. item.innerHTML = collectionHolder
  19. .dataset
  20. .prototype
  21. .replace(
  22. /__name__/g,
  23. collectionHolder.dataset.index
  24. );
  25. if (path !== '') {
  26. autocomplete(item, path);
  27. }
  28. collectionHolder.appendChild(item);
  29. addDeleteLink(item);
  30. collectionHolder.dataset.index++;
  31. };
  32. function addDeleteLink(item) {
  33. const input = item.querySelector('input') ?? item.querySelector('select');
  34. const deleteLink = document.createElement('button');
  35. deleteLink.className = 'btn btn-outline-secondary';
  36. const i = document.createElement('i');
  37. i.className = 'fa fa-trash fa-lg text-danger';
  38. deleteLink.appendChild(i);
  39. deleteLink.addEventListener("click", (event) => {
  40. item.remove();
  41. event.preventDefault(); // évite qu'un # apparaisse dans l'URL
  42. });
  43. input.after(deleteLink);
  44. };
  45. })();