(function ($) { $.fn.addCollection = function() { function requete(chemin, handleData) { $.ajax({ url: chemin, type: 'POST', dataType: 'json', success: function (reponse) { let reponseArray = parseJson(reponse); handleData(reponseArray); } }) } function parseJson(data) { let tableau = []; for (let i = 0; i < data.length; i++) { let UnObjetJson = data[i]; let obj = JSON.parse(UnObjetJson); sortie = Object.values(obj) tableau.push(sortie[0]); } return tableau; } function addDeleteLink($prototype) { // Création du lien let $deleteLink = $(''); // Ajout du lien $prototype.find(":input").after($deleteLink); // Ajout du listener sur le clic du lien pour effectivement supprimer la catégorie $deleteLink.on("click", function(e) { $prototype.remove(); e.preventDefault(); // évite qu'un # apparaisse dans l'URL return false; }); } this.each(function() { // Chemin pour la requête var chemin = $(this).data('path'); // On récupère le fieldset pour ajouter les delete-link aux éléments existants var $container = $($(this).attr("data-list-selector")); $li = $container.find('li'); $li.each(function() { if (chemin !== "") { $(this).find(':input').prop("readonly", true); } addDeleteLink($(this)); }) $(this).on("click", function(e) { e.preventDefault(); var list = jQuery(jQuery(this).attr('data-list-selector')); // Try to find the counter of the list or use the length of the list var counter = list.data('widget-counter') | list.children().length; // grab the prototype template var newWidget = list.attr('data-prototype'); // replace the "__name__" used in the id and name of the prototype // with a number that's unique to your emails // end name attribute looks like name="contact[emails][2]" newWidget = newWidget.replace(/__name__/g, counter); // Increase the counter counter++; // And store it, the length cannot be used if deleting widgets is allowed list.data('widget-counter', counter); // create a new list element and add it to the list var newElem = jQuery(list.attr('data-widget-tags')).html(newWidget); if (chemin !== "") { requete (chemin, function(output) { newElem.find(':input').autocomplete({ source: output }); }); } addDeleteLink(newElem); newElem.appendTo(list); }) }) } })(jQuery);