/* FUNCTIONS_FILL_TYPE_SUBTYPES The following functions populate the select for the types and subtypes when the category selected is changed */ document.getElementById('categories-properties').addEventListener('change', function() { var selectedValue = this.value; // Get the currently selected value
// Show a loading message in the property types dropdown var propertyTypesSelect = document.getElementById('propertyType'); propertyTypesSelect.innerHTML = '';
// Define the API endpoint var apiUrl = '/wp-json/agim-cs/v1/types';
// Prepare the data to be sent in the POST request var postData = { id: selectedValue };
// Use the Fetch API to send a POST request fetch(apiUrl, { method: 'POST', // Specify the method headers: { 'Content-Type': 'application/json' // Specify the content type as JSON }, body: JSON.stringify(postData) // Convert the JavaScript object to a JSON string }) .then(response => response.json()) // Parse the JSON response .then(data => { updatePropertyTypesDropdown(data); }) .catch((error) => { console.error('Error:', error); // Log an error if there is one propertyTypesSelect.innerHTML = ''; // Show error message if fetch fails }); });
function updatePropertyTypesDropdown(data) { var selectElement = document.getElementById('propertyType'); selectElement.innerHTML = ''; // Reset and add the default option
// Convert object to array using Object.values() Object.values(data).forEach(function(item) { var option = document.createElement('option'); option.value = item.id; option.textContent = item.name; selectElement.appendChild(option);
if (item.subtypes && Object.keys(item.subtypes).length > 0) { Object.values(item.subtypes).forEach(function(subtype) { var subOption = document.createElement('option'); subOption.value = subtype.id; subOption.innerHTML = ' ' + subtype.name; subOption.dataset.subtypeId = subtype.id; selectElement.appendChild(subOption); }); } }); }
/* END_FUNCTIONS_FILL_TYPE_SUBTYPES The following functions populate the select for the types and subtypes when the category selected is changed */
document.addEventListener('DOMContentLoaded', function() { fetchRegions(); });
function fetchRegions() { // Define the data you want to send in the POST request const postData = { type: 'regions' };
fetch('/wp-json/agim-cs/v1/localization', { method: 'POST', // Set the method to POST headers: { 'Content-Type': 'application/json', // Set the content type header }, body: JSON.stringify(postData) // Convert the postData object to a JSON string }) .then(response => response.json()) .then(regions => { const regionsDropdown = document.getElementById('regionsDropdown'); console.log(regions); regions.forEach(region => { const option = document.createElement('option'); option.value = region.id; option.textContent = region.name; regionsDropdown.appendChild(option); }); }) .catch(error => console.error('Error fetching regions:', error)); }
// Function to fetch all provinces function fetchAllProvinces() { const postData = { type: 'provinces' };
fetch('/wp-json/agim-cs/v1/localization', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(postData) }) .then(response => response.json()) .then(provinces => { populateDropdown('provincesDropdown', provinces); }) .catch(error => console.error('Error fetching all provinces:', error)); }
// Function to fetch all cities function fetchAllCities() { const postData = { type: 'cities' };
fetch('/wp-json/agim-cs/v1/localization', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(postData) }) .then(response => response.json()) .then(cities => { populateDropdown('citiesDropdown', cities); }) .catch(error => console.error('Error fetching all cities:', error)); }
// Function to fetch all districts function fetchAllDistricts() { const postData = { type: 'districts' };
fetch('/wp-json/agim-cs/v1/localization', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(postData) }) .then(response => response.json()) .then(districts => { populateDropdown('districtsDropdown', districts); }) .catch(error => console.error('Error fetching all districts:', error)); }
function fetchProvinces(regionId) { // Create an instance of FormData const formData = new FormData(); // Append parameters to the FormData object formData.append('type', 'provinces'); formData.append('id', regionId);
// Fetch provinces using the API endpoint with a POST request fetch('/wp-json/agim-cs/v1/localization', { method: 'POST', // Set the method to POST body: formData // Set the body to the formData object }) .then(response => response.json()) .then(provinces => { console.log(provinces); populateDropdown('provincesDropdown', provinces); }) .catch(error => console.error('Error fetching provinces:', error)); }
// Function to fetch cities based on the province ID function fetchCities(provinceId) { const formData = new FormData(); formData.append('type', 'cities'); formData.append('id', provinceId);
fetch('/wp-json/agim-cs/v1/localization', { method: 'POST', body: formData }) .then(response => response.json()) .then(cities => { populateDropdown('citiesDropdown', cities); console.log(cities) }) .catch(error => console.error('Error fetching cities:', error)); }
// Function to fetch districts based on the city ID function fetchDistricts(cityId) { const formData = new FormData(); formData.append('type', 'districts'); formData.append('id', cityId);
fetch('/wp-json/agim-cs/v1/localization', { method: 'POST', body: formData }) .then(response => response.json()) .then(districts => { populateDropdown('districtsDropdown', districts); }) .catch(error => console.error('Error fetching districts:', error)); }
// Helper function to populate a dropdown with options and include an empty first option function populateDropdown(dropdownId, items) { const dropdown = document.getElementById(dropdownId); // Clear existing options dropdown.innerHTML = '';
// Create and append the placeholder option const defaultOption = document.createElement('option'); defaultOption.value = ''; // Set the placeholder text based on the dropdownId switch (dropdownId) { case 'regionsDropdown': defaultOption.textContent = 'Seleziona una regione'; break; case 'provincesDropdown': defaultOption.textContent = 'Seleziona una provincia'; break; case 'citiesDropdown': defaultOption.textContent = 'Seleziona una città'; break; case 'districtsDropdown': defaultOption.textContent = 'Seleziona una zona'; break; default: defaultOption.textContent = 'Seleziona'; } dropdown.appendChild(defaultOption);
// Populate dropdown with new options items.forEach(item => { const option = document.createElement('option'); option.value = item.id; option.textContent = item.name; dropdown.appendChild(option); }); }
function resetDropdown(dropdownId, fetchAllFunction) { const dropdown = document.getElementById(dropdownId); dropdown.innerHTML = ``; if (fetchAllFunction) { fetchAllFunction(); } }
// Modify the event listener for regionsDropdown to include calls to fetchAllFunctions document.getElementById('regionsDropdown').addEventListener('change', function(event) { const regionId = event.target.value; if (regionId) { document.getElementById('provincesDropdown').disabled = false; fetchProvinces(regionId); } else { resetDropdown('provincesDropdown', fetchAllProvinces); resetDropdown('citiesDropdown', fetchAllCities); resetDropdown('districtsDropdown', fetchAllDistricts); } });
// Modify the event listener for provincesDropdown to include calls to fetchAllFunctions document.getElementById('provincesDropdown').addEventListener('change', function(event) { const provinceId = event.target.value; if (provinceId) { document.getElementById('citiesDropdown').disabled = false; fetchCities(provinceId); } else { resetDropdown('citiesDropdown', fetchAllCities); resetDropdown('districtsDropdown', fetchAllDistricts); } });
// The event listener for citiesDropdown should be modified in a similar manner // to include a call to fetchAllDistricts if no city is selected document.getElementById('citiesDropdown').addEventListener('change', function(event) { const cityId = event.target.value; if (cityId) { document.getElementById('districtsDropdown').disabled = false; fetchDistricts(cityId); } else { resetDropdown('districtsDropdown', fetchAllDistricts); } });
function fetchCities(provinceId) { const formData = new FormData(); formData.append('type', 'cities'); formData.append('id', provinceId);
fetch('/wp-json/agim-cs/v1/localization', { method: 'POST', body: formData }) .then(response => response.json()) .then(cities => { populateDropdown('citiesDropdown', cities); }) .catch(error => console.error('Error fetching cities:', error)); }
// Function to fetch districts based on the city ID function fetchDistricts(cityId) { const formData = new FormData(); formData.append('type', 'districts'); formData.append('id', cityId);
fetch('/wp-json/agim-cs/v1/localization', { method: 'POST', body: formData }) .then(response => response.json()) .then(districts => { populateDropdown('districtsDropdown', districts); }) .catch(error => console.error('Error fetching districts:', error)); }
document.getElementById('provincesDropdown').addEventListener('change', function(event) { const provinceId = event.target.value; if (provinceId) { document.getElementById('citiesDropdown').disabled = false; fetchCities(provinceId); } else { resetDropdown('citiesDropdown', fetchAllCities); resetDropdown('districtsDropdown', fetchAllDistricts); } });
// The event listener for citiesDropdown should be modified in a similar manner // to include a call to fetchAllDistricts if no city is selected document.getElementById('citiesDropdown').addEventListener('change', function(event) { const cityId = event.target.value; if (cityId) { document.getElementById('districtsDropdown').disabled = false; fetchDistricts(cityId); } else { resetDropdown('districtsDropdown', fetchAllDistricts); } });
//PROPERTY TYPE JS document.getElementById('propertyType').addEventListener('change', function() { var selectedOption = this.options[this.selectedIndex]; var isSubtype = selectedOption.hasAttribute('data-subtype-id');
// If the selected option has a data-subtype-id attribute, it's a subtype if (isSubtype) { this.name = 'property_subtype_id'; } else { this.name = 'property_type_id'; } });
// Function to clear all other input and select fields function clearOtherInputs() { var otherInputs = document.querySelectorAll('#agim-search-form input:not([name="code"]):not([type="submit"]):not([type="hidden"]), #agim-search-form select'); otherInputs.forEach(function(input) { input.value = ''; }); }
// Function to enable or disable other inputs based on the "code" input's value and clear them if necessary function toggleOtherInputs() { var codeInput = document.querySelector('#agim-search-form input[name="code"]'); var isCodeEmpty = codeInput.value.trim() === '';
// Get a NodeList of all input elements except the "code" input, submit button, hidden inputs, and the select elements var inputs = document.querySelectorAll('#agim-search-form input:not([name="code"]):not([type="submit"]):not([type="hidden"]), #agim-search-form select'); // Get the message div var messageDiv = document.getElementById('code-search-message');
// If code is not empty and other inputs are not already disabled, clear them if (!isCodeEmpty) { var otherInputsFilled = Array.from(inputs).some(input => input.value.trim() !== ''); if (otherInputsFilled) { clearOtherInputs(); } }
// Loop through the NodeList and set the disabled property based on isCodeEmpty inputs.forEach(function(input) { input.disabled = !isCodeEmpty; });
// Update the message div content based on whether the code input is empty messageDiv.textContent = isCodeEmpty ? '' : "Stai effettuando una ricerca per codice, tutti gli altri campi sono stati disabilitati."; }
// Event listener for the "code" input document.querySelector('#agim-search-form input[name="code"]').addEventListener('input', toggleOtherInputs);
// Add event listeners to all other input and select elements to show an alert if the "code" field is not empty document.querySelectorAll('#agim-search-form input:not([name="code"]):not([type="submit"]):not([type="hidden"]), #agim-search-form select').forEach(function(input) { input.addEventListener('focus', showAlertIfCodeNotEmpty); });
// Initial call to ensure proper state upon page load toggleOtherInputs();
function updateOutput(outputId, value) { document.getElementById(outputId).textContent = value; }
//GARAGE FUNCITON SELECTOR
function toggleGarageSelector() { // Get the checkbox and the dropdown selector var garageCheckbox = document.getElementById('garage-checkbox'); var garageType = document.getElementById('garage-type');
// Enable or disable the dropdown based on the checkbox status garageType.disabled = !garageCheckbox.checked; }
function updateHiddenInput() { // Get all checked checkboxes within the checkbox group var checkboxes = document.querySelectorAll('#checkbox-group input[type="checkbox"]:checked');
// Get the button with the class 'dropbtn' var button = document.querySelector('.dropbtn');
// Map checked checkboxes to their corresponding label text, excluding the checkbox text content var checkboxLabels = Array.from(checkboxes).map(function(checkbox) { // Get the whole text of the label, then trim it to remove excess whitespace var fullLabel = checkbox.parentNode.textContent.trim(); // Optional: Remove extra spaces due to formatting in the HTML return fullLabel.replace(/\s+/g, ' '); });
// Update the button text with selected category names or reset to default text if none are selected if (checkboxLabels.length > 0) { button.textContent = 'Seleziona una o più categorie: ' + checkboxLabels.join(', '); } else { button.textContent = 'Seleziona una o più categorie'; }
// Get values from checked checkboxes and join them with a semicolon var selectedValues = Array.from(checkboxes).map(checkbox => checkbox.value); var joinedValues = selectedValues.join(';');
// Update the hidden input's value document.getElementById('categories-properties').value = joinedValues; updateCategories(joinedValues, 'propertyType','propertyType') // Log the hidden input's value to the console for debugging console.log('categories-properties values', document.getElementById('categories-properties').value); }
function updateCategories(selectedValue, primarySelectId, secondarySelectId) { console.log(selectedValue) var primarySelect = document.getElementById(primarySelectId); primarySelect.innerHTML = ''; var secondarySelect = document.getElementById(secondarySelectId); secondarySelect.innerHTML = '';
var apiUrl = '/wp-json/agim-cs/v1/types'; var postData = { id: selectedValue };
fetch(apiUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(postData) }) .then(response => response.json()) .then(data => { updatePropertyTypesDropdown(data, primarySelectId, secondarySelectId); }) .catch((error) => { console.error('Error:', error); primarySelect.innerHTML = ''; secondarySelect.innerHTML = ''; }); }