addCollectionVanilla.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import { autocomplete } from './autocomplete'
  2. (() => {
  3. document
  4. .querySelectorAll('ul.collection-form li')
  5. .forEach(item => {
  6. item.querySelector('input').readOnly = 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.type = 'button';
  37. deleteLink.className = 'btn btn-outline-secondary';
  38. const i = document.createElement('i');
  39. i.className = 'fa fa-trash fa-lg text-danger';
  40. deleteLink.appendChild(i);
  41. deleteLink.addEventListener("click", (event) => {
  42. item.remove();
  43. event.preventDefault(); // évite qu'un # apparaisse dans l'URL
  44. });
  45. input.after(deleteLink);
  46. };
  47. })();