addCollectionVanilla.js 1.6 KB

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