/* javascript form handling */ document.addEventListener("DOMContentLoaded", function () { const newNkInput = document.getElementById("new-negative-keyword"); if (newNkInput) { newNkInput.addEventListener("input", function () { const val = this.value.trim(); const existing = Array.from( document.querySelectorAll('input[name="negative_keyword"]') ).map((el) => el.value); if (existing.includes(val)) { this.setCustomValidity("Keyword already exists"); this.reportValidity(); } else { this.setCustomValidity(""); } }); } }); document .getElementById("user-settings-form") .addEventListener("submit", function (event) { event.preventDefault(); // Prevent default form submission const form = event.target; const formData = new FormData(form); // Collect selected regions and keywords const selectedRegions = []; const selectedKeywords = []; const selectedNegativeKeywords = []; formData.forEach((value, key) => { if (key === "region") { selectedRegions.push(value); } else if (key === "keyword") { selectedKeywords.push(value); } else if (key === "negative_keyword") { selectedNegativeKeywords.push(value); } }); // Add new region if provided const newRegion = formData.get("new-region").trim(); if (newRegion) { selectedRegions.push(newRegion); } // Add new keyword if provided const newKeyword = formData.get("new-keyword").trim(); if (newKeyword) { selectedKeywords.push(newKeyword); } // Add new negative keyword if provided const newNegativeKeyword = formData.get("new-negative-keyword").trim(); if (newNegativeKeyword) { if (selectedNegativeKeywords.includes(newNegativeKeyword)) { alert("Negative keyword already exists!"); return; } selectedNegativeKeywords.push(newNegativeKeyword); } // Prepare data to send const dataToSend = { regions: selectedRegions, keywords: selectedKeywords, negative_keywords: selectedNegativeKeywords, csrf_token: formData.get("csrf_token"), }; // Send data via Fetch API fetch(form.action, { method: "POST", headers: { "Content-Type": "application/json", "X-CSRF-Token": document.querySelector('meta[name="csrf-token"]') .content, }, body: JSON.stringify(dataToSend), }) .then((response) => { if (response.ok) { window.location.reload(); // Reload to reflect changes } else { alert("Error saving preferences."); } }) .catch((error) => { console.error("Error:", error); alert("Error saving preferences."); }); });