DEV Community

MUHAMMAD AHMED AMIR
MUHAMMAD AHMED AMIR

Posted on

I have issue in form

I have issue in js code that I want to add predictive text inside input field from Google's Locations API

The code is
let currentStep = 0;

function initAutocomplete() {
const input = document.getElementById("address");
const autocomplete = new google.maps.places.Autocomplete(input, {
types: ["address"],
strictBounds: true
});

autocomplete.addListener("place_changed", function() {
    const place = autocomplete.getPlace();

    const desiredCities = ["Washington, DC"];
    const desiredZipCodes = [];
    const desiredCounties = [];
    const desiredStates = ["DC"];

    let isState = true;
    let isCity = true;
    let isZipCode = true;
    let isCounty = true;

    let cityName = "";
    let countyName = "";
    let stateName = "";

    place.address_components.forEach(component => {
        if (component.types.includes("locality")) {
            cityName = component.long_name;
        }

        if (desiredZipCodes.length) {
            if (component.types.includes("postal_code")) {
                isZipCode = desiredZipCodes.includes(component.short_name);
            }
        }

        if (component.types.includes("administrative_area_level_2")) {
            countyName = component.long_name;
        }

        if (component.types.includes("administrative_area_level_1")) {
            stateName = component.short_name;
            if (desiredStates.length) {
                isState = desiredStates.includes(stateName);
            }
        }
    });

    if (cityName && stateName && desiredCities.length) {
        const cityStateCombo = `${cityName}, ${stateName}`;
        isCity = desiredCities.includes(cityStateCombo);
    }

    if (countyName && stateName && desiredCounties.length) {
        const countyStateCombo = `${countyName}, ${stateName}`;
        isCounty = desiredCounties.includes(countyStateCombo);
    }

    const isDesiredLocation = isCity && isZipCode && isCounty && isState;

    document.getElementById("is-florida").value = isDesiredLocation ? "true" : "false";
    document.getElementById("next-btn").disabled = !isDesiredLocation;

    if (!isDesiredLocation) {
        showErrorMessage("address-error", "We are not interested in this area.");
    } else {
        hideErrorMessage("address-error");
        changeStep(1);
    }
});



document.getElementById('address').addEventListener('input', async function() {
    const query = this.value;
    const datalist = document.getElementById('address-suggestions');
    datalist.innerHTML = ''; // Clear existing options

    if (query.length < 3) return; // Minimum 3 characters for suggestions

    try {
        const response = await fetch(`https://maps.googleapis.com/maps/api/place/autocomplete/json?input=${encodeURIComponent(query)}&key=YOUR_API_KEY`);
        const data = await response.json();

        data.predictions.forEach(prediction => {
            const option = document.createElement('option');
            option.value = prediction.description; // Use description for suggestions
            datalist.appendChild(option);
        });
    } catch (error) {
        console.error('Error fetching suggestions:', error);
    }
});











input.addEventListener("input", function() {
    document.getElementById("next-btn").disabled = true;
    if (input.value.trim() === "") {
        showErrorMessage("address-error", "Address is required");
    } else {
        hideErrorMessage("address-error");
    }
});
Enter fullscreen mode Exit fullscreen mode

}

const totalSteps = 10; // Change this to the number of steps

function updateProgressBar() {
const progressBar = document.getElementById("progress-bar");
const progressText = document.getElementById("progress-text");
const progress = ((currentStep + 1) / totalSteps) * 100;

progressBar.style.width = Math.min(100, progress) + "%";
progressText.innerText = `${Math.round(progress)}%`;
Enter fullscreen mode Exit fullscreen mode

}

function showStep(step) {
const steps = document.querySelectorAll(".step");
steps.forEach((s, index) => s.classList.toggle("active", index === step));
updateProgressBar();
}

function changeStep(n) {
if (currentStep + n < 0 || currentStep + n >= totalSteps) return;

currentStep += n;
showStep(currentStep);
Enter fullscreen mode Exit fullscreen mode

}

function showStep(step) {
const steps = document.querySelectorAll(".step");
steps.forEach((step) => step.style.display = "none");
steps[step].style.display = "block";

document.getElementById("prev-btn").style.display = step === 0 ? "none" : "inline";
document.getElementById("next-btn").style.display = step === steps.length - 1 ? "none" : "inline";
document.getElementById("submit-btn").style.display = step === steps.length - 1 ? "inline" : "none";

updateProgressBar();

if (step === 0) {
    const input = document.getElementById("address");
    input.value = '';
    document.getElementById("is-florida").value = "false";
}
Enter fullscreen mode Exit fullscreen mode

}

function changeStep(n) {
const steps = document.querySelectorAll(".step");
if (n > 0 && !validateForm()) return false;

steps[currentStep].style.display = "none";
currentStep += n;

if (currentStep >= steps.length) {
    submitFormToWebhook();
    return false;
}

showStep(currentStep);
updateProgressBar();
Enter fullscreen mode Exit fullscreen mode

}

function validateForm() {
const steps = document.querySelectorAll(".step");
const inputs = steps[currentStep].querySelectorAll("input, select, textarea");
let valid = true;

inputs.forEach(input => {
    let errorId = input.id ? `${input.id}-error` : `${input.name}-error`;
    const errorElement = document.getElementById(errorId);

    if (input.type === "radio" && !document.querySelector(`input[name="${input.name}"]:checked`)) {
        valid = false;
        if (errorElement) showErrorMessage(errorId, "This field is required.");
    } else if (input.type === "email") {
        if (!validateEmail(input.value)) {
            valid = false;
            if (errorElement) showErrorMessage(errorId, "Please enter a valid email address.");
        } else {
            if (errorElement) hideErrorMessage(errorId);
        }
    } else if (input.name === "full-name") {
        if (!input.value) {
            valid = false;
            if (errorElement) showErrorMessage(errorId, "Please enter your full name.");
        } else {
            if (errorElement) hideErrorMessage(errorId);
        }
    } else if (input.name === "phone-number") {
        if (!validatePhoneNumber(input.value)) {
            valid = false;
            if (errorElement) showErrorMessage(errorId, "Please enter a valid phone number.");
        } else {
            if (errorElement) hideErrorMessage(errorId);
        }
    } else if (input.value.trim() === "") {
        valid = false;
        if (errorElement) showErrorMessage(errorId, "This field is required.");
    } else {
        if (errorElement) hideErrorMessage(errorId);
    }
});

return valid;
Enter fullscreen mode Exit fullscreen mode

}

function validateEmail(email) {
const emailPattern = /^[^\s@]+@[^\s@]+.[^\s@]+$/;
return emailPattern.test(email);
}

function validatePhoneNumber(phone) {
const usCaPhonePattern = /^(+?1\s?)?((?\d{3})?[\s.-]?)?\d{3}[\s.-]?\d{4}$/;
return usCaPhonePattern.test(phone);
}

function showErrorMessage(id, message) {
const errorDiv = document.getElementById(id);
if (errorDiv) {
errorDiv.innerText = message;
errorDiv.style.display = "block";
}
}

function hideErrorMessage(id) {
const errorDiv = document.getElementById(id);
if (errorDiv) {
errorDiv.style.display = "none";
}
}

function submitFormToWebhook() {
const form = document.getElementById("property-form");
const formData = new FormData(form);

fetch('https://services.leadconnectorhq.com/hooks/LrWypu7aGiHXi4GJFeaJ/webhook-trigger/61d241b7-94c3-4828-9838-8d7054ab7da5', {
    method: 'POST',
    body: formData
})
.then(response => response.json())
.then(data => {
    console.log('Success:', data);
    showSuccessMessage();
})
.catch(error => console.error('Error:', error));
Enter fullscreen mode Exit fullscreen mode

}

function showSuccessMessage() {
document.querySelector('.form-container').style.display = 'none';
const successMessageDiv = document.getElementById('success-message');
successMessageDiv.innerHTML = "

Survey submitted successfully!

";
successMessageDiv.style.textAlign = 'center';
successMessageDiv.style.marginTop = '20px';
}

console.log('currentStep', currentStep);
showStep(currentStep);
initAutocomplete();

const form = document.getElementById("property-form");
form.addEventListener("submit", function(event) {
event.preventDefault();
if (validateForm()) {
submitFormToWebhook();
}
});

const propertyTypeSelect = document.getElementById("property-type");
propertyTypeSelect.addEventListener("change", function() {
if (currentStep === 1 && this.value === "mobile-home") {
showErrorMessage("property-type-error", "We are not interested in this type of home");
document.getElementById("next-btn").disabled = true;
} else {
hideErrorMessage("property-type-error");
document.getElementById("next-btn").disabled = false;
}
});

document.getElementById("phone-number").addEventListener("input", function(event) {
let input = event.target.value.replace(/\D/g, '');
if (input.length > 0) {
input = input.substring(0, 10);
}

if (input.length > 6) {
    input = `(${input.substring(0, 3)}) ${input.substring(3, 6)}-${input.substring(6, 10)}`;
} else if (input.length > 3) {
    input = `(${input.substring(0, 3)}) ${input.substring(3, 6)}`;
} else if (input.length > 0) {
    input = `(${input}`;
}

event.target.value = input;
Enter fullscreen mode Exit fullscreen mode

});

Top comments (0)