ajax-tags.js (2038B)
1 2 function initAjaxTagForms() { 3 document.querySelectorAll('.ajax-tag-form').forEach((form) => { 4 if (form.dataset.ajaxBound) return; // avoid double-binding after a swap 5 form.dataset.ajaxBound = 'true'; 6 form.addEventListener('submit', handleAjaxTagSubmit); 7 }); 8 } 9 10 async function handleAjaxTagSubmit(e) { 11 e.preventDefault(); 12 const form = e.target; 13 const submitButton = form.querySelector('button[type="submit"]'); 14 if (submitButton) submitButton.disabled = true; 15 16 const action = form.getAttribute('action') || window.location.pathname; 17 18 try { 19 const response = await fetch(action, { 20 method: 'POST', 21 body: new FormData(form), 22 }); 23 24 if (!response.ok) { 25 throw new Error('Request failed with status ' + response.status); 26 } 27 28 const html = await response.text(); 29 const doc = new DOMParser().parseFromString(html, 'text/html'); 30 31 // Swap the tag list 32 const newTagsList = doc.getElementById('tags-list'); 33 const currentTagsList = document.getElementById('tags-list'); 34 if (newTagsList && currentTagsList) { 35 currentTagsList.innerHTML = newTagsList.innerHTML; 36 } 37 38 // Swap the category datalist (new categories may have been created) 39 const newCategories = doc.getElementById('categories'); 40 const currentCategories = document.getElementById('categories'); 41 if (newCategories && currentCategories) { 42 currentCategories.innerHTML = newCategories.innerHTML; 43 } 44 45 // Clear the "Add Tag" inputs after a submit 46 const catInput = form.querySelector('input[name="category"]'); 47 const valInput = form.querySelector('input[name="value"]'); 48 if (catInput && valInput) { 49 catInput.value = ''; 50 valInput.value = ''; 51 catInput.focus(); 52 } 53 54 // Re-bind the delete buttons that just got swapped in 55 initAjaxTagForms(); 56 } catch (err) { 57 console.error('Tag update failed:', err); 58 } finally { 59 if (submitButton) submitButton.disabled = false; 60 } 61 } 62 63 document.addEventListener('DOMContentLoaded', initAjaxTagForms);