<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: MUHAMMAD AHMED AMIR</title>
    <description>The latest articles on DEV Community by MUHAMMAD AHMED AMIR (@muhammad_ahmedamir_e4b59).</description>
    <link>https://dev.to/muhammad_ahmedamir_e4b59</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F2213996%2F2ffd1755-daf9-443c-a021-f7b29101c29f.jpg</url>
      <title>DEV Community: MUHAMMAD AHMED AMIR</title>
      <link>https://dev.to/muhammad_ahmedamir_e4b59</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/muhammad_ahmedamir_e4b59"/>
    <language>en</language>
    <item>
      <title>I have issue in form</title>
      <dc:creator>MUHAMMAD AHMED AMIR</dc:creator>
      <pubDate>Tue, 15 Oct 2024 08:24:51 +0000</pubDate>
      <link>https://dev.to/muhammad_ahmedamir_e4b59/i-have-issue-in-form-2g5b</link>
      <guid>https://dev.to/muhammad_ahmedamir_e4b59/i-have-issue-in-form-2g5b</guid>
      <description>&lt;p&gt;I have issue in js code that I want to add predictive text inside input field from Google's Locations API&lt;/p&gt;

&lt;p&gt;The code is&lt;br&gt;
let currentStep = 0;&lt;/p&gt;

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

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;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 =&amp;gt; {
        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 &amp;amp;&amp;amp; stateName &amp;amp;&amp;amp; desiredCities.length) {
        const cityStateCombo = `${cityName}, ${stateName}`;
        isCity = desiredCities.includes(cityStateCombo);
    }

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

    const isDesiredLocation = isCity &amp;amp;&amp;amp; isZipCode &amp;amp;&amp;amp; isCounty &amp;amp;&amp;amp; 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 &amp;lt; 3) return; // Minimum 3 characters for suggestions

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

        data.predictions.forEach(prediction =&amp;gt; {
            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");
    }
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}&lt;/p&gt;

&lt;p&gt;const totalSteps = 10; // Change this to the number of steps&lt;/p&gt;

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

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;progressBar.style.width = Math.min(100, progress) + "%";
progressText.innerText = `${Math.round(progress)}%`;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}&lt;/p&gt;

&lt;p&gt;function showStep(step) {&lt;br&gt;
    const steps = document.querySelectorAll(".step");&lt;br&gt;
    steps.forEach((s, index) =&amp;gt; s.classList.toggle("active", index === step));&lt;br&gt;
    updateProgressBar();&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;function changeStep(n) {&lt;br&gt;
    if (currentStep + n &amp;lt; 0 || currentStep + n &amp;gt;= totalSteps) return;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;currentStep += n;
showStep(currentStep);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}&lt;/p&gt;

&lt;p&gt;function showStep(step) {&lt;br&gt;
    const steps = document.querySelectorAll(".step");&lt;br&gt;
    steps.forEach((step) =&amp;gt; step.style.display = "none");&lt;br&gt;
    steps[step].style.display = "block";&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;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";
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}&lt;/p&gt;

&lt;p&gt;function changeStep(n) {&lt;br&gt;
    const steps = document.querySelectorAll(".step");&lt;br&gt;
    if (n &amp;gt; 0 &amp;amp;&amp;amp; !validateForm()) return false;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;steps[currentStep].style.display = "none";
currentStep += n;

if (currentStep &amp;gt;= steps.length) {
    submitFormToWebhook();
    return false;
}

showStep(currentStep);
updateProgressBar();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}&lt;/p&gt;

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

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;inputs.forEach(input =&amp;gt; {
    let errorId = input.id ? `${input.id}-error` : `${input.name}-error`;
    const errorElement = document.getElementById(errorId);

    if (input.type === "radio" &amp;amp;&amp;amp; !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;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}&lt;/p&gt;

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

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

&lt;p&gt;function showErrorMessage(id, message) {&lt;br&gt;
    const errorDiv = document.getElementById(id);&lt;br&gt;
    if (errorDiv) {&lt;br&gt;
        errorDiv.innerText = message;&lt;br&gt;
        errorDiv.style.display = "block";&lt;br&gt;
    }&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;function hideErrorMessage(id) {&lt;br&gt;
    const errorDiv = document.getElementById(id);&lt;br&gt;
    if (errorDiv) {&lt;br&gt;
        errorDiv.style.display = "none";&lt;br&gt;
    }&lt;br&gt;
}&lt;/p&gt;

&lt;p&gt;function submitFormToWebhook() {&lt;br&gt;
    const form = document.getElementById("property-form");&lt;br&gt;
    const formData = new FormData(form);&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fetch('https://services.leadconnectorhq.com/hooks/LrWypu7aGiHXi4GJFeaJ/webhook-trigger/61d241b7-94c3-4828-9838-8d7054ab7da5', {
    method: 'POST',
    body: formData
})
.then(response =&amp;gt; response.json())
.then(data =&amp;gt; {
    console.log('Success:', data);
    showSuccessMessage();
})
.catch(error =&amp;gt; console.error('Error:', error));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}&lt;/p&gt;

&lt;p&gt;function showSuccessMessage() {&lt;br&gt;
    document.querySelector('.form-container').style.display = 'none';&lt;br&gt;
    const successMessageDiv = document.getElementById('success-message');&lt;br&gt;
    successMessageDiv.innerHTML = "&lt;/p&gt;
&lt;h2&gt;Survey submitted successfully!&lt;/h2&gt;";&lt;br&gt;
    successMessageDiv.style.textAlign = 'center';&lt;br&gt;
    successMessageDiv.style.marginTop = '20px';&lt;br&gt;
}

&lt;p&gt;console.log('currentStep', currentStep);&lt;br&gt;
showStep(currentStep);&lt;br&gt;
initAutocomplete();&lt;/p&gt;

&lt;p&gt;const form = document.getElementById("property-form");&lt;br&gt;
form.addEventListener("submit", function(event) {&lt;br&gt;
    event.preventDefault();&lt;br&gt;
    if (validateForm()) {&lt;br&gt;
        submitFormToWebhook();&lt;br&gt;
    }&lt;br&gt;
});&lt;/p&gt;

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

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

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if (input.length &amp;gt; 6) {
    input = `(${input.substring(0, 3)}) ${input.substring(3, 6)}-${input.substring(6, 10)}`;
} else if (input.length &amp;gt; 3) {
    input = `(${input.substring(0, 3)}) ${input.substring(3, 6)}`;
} else if (input.length &amp;gt; 0) {
    input = `(${input}`;
}

event.target.value = input;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;});&lt;/p&gt;

</description>
      <category>form</category>
    </item>
  </channel>
</rss>
