// 1. Listen for the Search Button Click or Enter Key document.addEventListener('click', handleSearchValidation, true); document.addEventListener('keydown', (event) => { if (event.key === 'Enter') handleSearchValidation(event); }, true); // 2. NEW: Listen for "input" events to remove error while typing document.addEventListener('input', (event) => { const inputField = event.target.closest('.plpSearchClass input[type="search"]'); if (inputField && inputField.value.trim() !== '') { const container = inputField.closest('commerce_builder-search-input'); clearSearchError(container); } }, true); function handleSearchValidation(event) { const target = event.target; const searchButton = target.closest('.plpSearchClass .input-search-button'); const isEnterKey = event.key === 'Enter' && target.closest('.plpSearchClass input[type="search"]'); if (searchButton || isEnterKey) { const container = target.closest('commerce_builder-search-input'); const inputField = container.querySelector('input[type="search"]'); if (!inputField.value || inputField.value.trim() === '') { event.preventDefault(); event.stopPropagation(); showSearchError(container, getTranslatedErrorMessage()); } else { clearSearchError(container); } } } function getTranslatedErrorMessage() { const messages = { 'it': 'Per favore inserisci un termine di ricerca.', 'fr': 'Veuillez saisir un terme de recherche.', 'es': 'Por favor ingrese un término de búsqueda.', 'de': 'Bitte geben Sie einen Suchbegriff ein.', 'en': 'Please enter a search term.' }; const path = window.location.pathname; let lang = 'en'; if (path.includes('/it/')) lang = 'it'; else if (path.includes('/fr/')) lang = 'fr'; else if (path.includes('/es/')) lang = 'es'; else if (path.includes('/de/')) lang = 'de'; return messages[lang] || messages['en']; } function showSearchError(container, message) { clearSearchError(container); const errorDiv = document.createElement('div'); errorDiv.className = 'custom-search-error slds-text-color_error slds-m-top_xx-small'; errorDiv.style.cssText = 'font-size: 12px; font-weight: bold; padding-left: 5px; animation: fadeIn 0.3s;'; errorDiv.innerText = message; container.appendChild(errorDiv); const inputWrapper = container.querySelector('.input-wrapper'); if (inputWrapper) { inputWrapper.style.border = '2px solid #c23934'; inputWrapper.style.boxShadow = '0 0 4px rgba(194, 57, 52, 0.5)'; } } function clearSearchError(container) { const existingError = container.querySelector('.custom-search-error'); if (existingError) existingError.remove(); const inputWrapper = container.querySelector('.input-wrapper'); if (inputWrapper) { inputWrapper.style.border = ''; inputWrapper.style.boxShadow = ''; } }