Custom JavaScript not working on a specific page

Hello!

I use a custom JavaScript script on the contact forms of my website to apply input masks and field validations. The form is Webflow’s native form element, and I include the script in the page’s <body>. Everything works perfectly on all pages of the site except the homepage — it’s like the script isn’t being loaded at all there, so the form doesn’t behave as expected.

I’ve already checked Google Tag Manager for possible conflicts, but everything seems fine. There are also no error messages in the Chrome console, so I’m pretty much in the dark on this one.

Has anyone else run into something similar?


Share a link to the homepage, and to a working page, along with an excerpt of the script to see which script you’re talking about.

Are you loading it in before-/body on each page individually?

Generally you’d put a console.log in your script so that you can tell if it’s loading.

ok!

here is the link to the page that im working on:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/css/intlTelInput.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/js/intlTelInput.min.js"></script>
<script>
//validacao de formulário
document.addEventListener('DOMContentLoaded', function() {
    const phoneField = document.getElementById('contact-phone-input');
    const emailField = document.getElementById('contact-email-input');
    const websiteField = document.getElementById('contact-company-website-input');
    const nameField = document.getElementById('contact-name-input');
    const submitButton = document.getElementById('submit-btn');
    const phoneError = document.getElementById('phone-error');
    const emailWarning = document.getElementById('email-warning');
    const emailError = document.getElementById('email-error');
    const websiteError = document.getElementById('website-error');
    const nameError = document.getElementById('name-error');
    const dddError = document.getElementById('ddd-error');
    const vendasCheckbox = document.getElementById('vendas-checkbox');
    const vendasOptions = document.getElementById('company-sales-struggle-wrapper');
    const atendimentoCheckbox = document.getElementById('atendimento-checkbox');
    const atendimentoOptions = document.getElementById('company-service-struggle-wrapper');

    const publicDomains = ["gmail.com", "hotmail.com", "yahoo.com", "outlook.com"];

    function applyPhoneMask(value) {
        value = value.replace(/\D/g, "");
        if (value.length > 10) {
            return (${value.slice(0, 2)}) ${value.slice(2, 7)}-${value.slice(7, 11)};
        } else if (value.length > 6) {
            return (${value.slice(0, 2)}) ${value.slice(2, 6)}-${value.slice(6)};
        } else if (value.length > 2) {
            return (${value.slice(0, 2)}) ${value.slice(2)};
        } else {
            return value;
        }
    }

    function validateName(name) {
        const nameRegex = /^[a-zA-ZÀ-ÿ\s]+$/;
        const nameParts = name.trim().split(/\s+/);
        return nameParts.length >= 2 && nameParts.every(part => part.length > 1 && nameRegex.test(part));
    }

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

    function checkPublicDomain(email) {
        const domain = email.split('@')[1];
        return publicDomains.includes(domain);
    }

    function validateWebsite(website) {
        const websiteRegex = /^(https?:\/\/)?[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(\.[a-zA-Z]{2,})?(\/[a-zA-Z0-9.-]*)*$/;
        return websiteRegex.test(website);
    }

    function checkWebsitePublicDomain(website) {
        let domain = website.replace(/^(https?:\/\/)?(www\.)?/, '').split('/')[0];
        return publicDomains.some(publicDomain => domain.endsWith(publicDomain));
    }

    const iti = window.intlTelInput(phoneField, {
        initialCountry: "br",
        separateDialCode: true,
        utilsScript: "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/js/utils.js"
    });

    function getFullPhoneNumber() {
        return iti.getNumber(intlTelInputUtils.numberFormat.E164);
    }

    function validatePhone() {
        const isValidPhone = iti.isValidNumber();
        const phoneDigits = iti.getNumber().replace(/\D/g, '');

        if (iti.getSelectedCountryData().iso2 === 'br') {
            const ddd = phoneDigits.substring(0, 2);
            const validDDD = [11, 12, 13, 14, 15, 16, 17, 18, 19, 21, 22, 24, 27, 28, 31, 32, 33, 34, 35, 37, 38, 41, 42, 43, 44, 45, 46, 47, 48, 49, 51, 53, 54, 55, 61, 62, 63, 64, 65, 66, 67, 68, 69, 71, 73, 74, 75, 77, 79, 81, 82, 83, 84, 85, 86, 87, 88, 89, 91, 92, 93, 94, 95, 96, 97, 98, 99];
            if (!validDDD.includes(parseInt(ddd))) {
                return { isValid: false, isDDDInvalid: true };
            }
        }
        return { isValid: isValidPhone, isDDDInvalid: false };
    }

    function checkFormValidity() {
        const isFormValid = validatePhone(phoneField.value).isValid 
            && validateWebsite(websiteField.value) 
            && validateName(nameField.value)
            && validateEmailFormat(emailField.value)
            && !checkPublicDomain(emailField.value);

        submitButton.classList.toggle('disabled-btn', !isFormValid);
    }

    function handleCheckboxChange() {
        if (vendasCheckbox.checked) {
            vendasOptions.style.display = 'block';
            atendimentoOptions.style.display = 'none';
            atendimentoCheckbox.checked = false;
        } else {
            vendasOptions.style.display = 'none';
        }

        if (atendimentoCheckbox.checked) {
            atendimentoOptions.style.display = 'block';
            vendasOptions.style.display = 'none';
            vendasCheckbox.checked = false;
        } else {
            atendimentoOptions.style.display = 'none';
        }
    }

    function checkFieldValidity(field) {
        if (field === nameField) {
            let isNameValid = validateName(nameField.value);
            nameError.style.display = isNameValid ? 'none' : 'block';
            nameField.style.borderColor = isNameValid ? 'green' : 'red';
        }

        if (field === phoneField) {
            let validation = validatePhone(phoneField.value);
            phoneError.style.display = validation.isValid ? 'none' : 'block';
            dddError.style.display = validation.isDDDInvalid ? 'block' : 'none';
            phoneField.style.borderColor = validation.isValid ? 'green' : 'red';
        }

        if (field === emailField) {
            let isEmailValid = validateEmailFormat(emailField.value);
            let isEmailPublic = checkPublicDomain(emailField.value);
            emailError.style.display = isEmailValid ? 'none' : 'block';
            emailWarning.style.display = isEmailPublic ? 'block' : 'none';
            emailField.style.borderColor = isEmailValid && !isEmailPublic ? 'green' : 'red';
        }

        if (field === websiteField) {
            let isWebsiteValid = validateWebsite(websiteField.value);
            let isWebsitePublic = checkWebsitePublicDomain(websiteField.value);
            websiteError.style.display = isWebsiteValid && !isWebsitePublic ? 'none' : 'block';
            websiteField.style.borderColor = isWebsiteValid && !isWebsitePublic ? 'green' : 'red';
        }

        checkFormValidity();
    }

    vendasCheckbox.addEventListener('change', handleCheckboxChange);
    atendimentoCheckbox.addEventListener('change', handleCheckboxChange);

    nameField.addEventListener('blur', () => checkFieldValidity(nameField));
    phoneField.addEventListener('blur', () => checkFieldValidity(phoneField));
    emailField.addEventListener('blur', () => checkFieldValidity(emailField));
    websiteField.addEventListener('blur', () => checkFieldValidity(websiteField));

    nameField.addEventListener('input', () => checkFieldValidity(nameField));
    phoneField.addEventListener('input', () => { phoneField.value = applyPhoneMask(phoneField.value); checkFieldValidity(phoneField); });
    emailField.addEventListener('input', () => checkFieldValidity(emailField));
    websiteField.addEventListener('input', () => checkFieldValidity(websiteField));

    document.getElementById('wf-form-contact-form-9').addEventListener('submit', function(e) {
        if (submitButton.classList.contains('disabled-btn')) {
            e.preventDefault();
            alert("Por favor, preencha o formulário corretamente.");
        } else {
            phoneField.value = getFullPhoneNumber();
        }
    });
});

// Configura o cookie last_utm e captura o GCLID
const params = new URLSearchParams(window.location.search);

// Captura os parâmetros das UTMs
const utm_source = params.get('utm_source') || '';
const utm_medium = params.get('utm_medium') || '';
const utm_campaign = params.get('utm_campaign') || '';
const utm_term = params.get('utm_term') || '';
const utm_content = params.get('utm_content') || '';

// Captura o parâmetro GCLID
const gclid = params.get('gclid') || '';

// Armazena as UTMs e o GCLID em cookies
const lastUtmValue = ${utm_source}|${utm_medium}|${utm_campaign}|${utm_term}|${utm_content}|${gclid};
if (lastUtmValue !== '|||||') {
  document.cookie = last_utm=${lastUtmValue}; path=/; max-age=2592000;; // Expira em 30 dias
}

// Preenche os campos do formulário
function callCookieLastUtm() {
  const cookies = document.cookie;
  const utmCookie = cookies.split('; ').find((row) => row.startsWith('last_utm='));

  if (utmCookie) {
    // Extrai as UTMs e o GCLID do cookie
    const [utm_source, utm_medium, utm_campaign, utm_term, utm_content, gclid] = utmCookie.split('=')[1].split('|');

    const setFieldValue = (id, value) => {
      const field = document.getElementById(id);
      if (field) field.value = value || '';
    };

    // Preenche os campos de UTMs
    setFieldValue('utm_source', utm_source);
    setFieldValue('utm_medium', utm_medium);
    setFieldValue('utm_campaign', utm_campaign);
    setFieldValue('utm_term', utm_term);
    setFieldValue('utm_content', utm_content);

    // Preenche o campo oculto do GCLID
    setFieldValue('gclid', gclid);
  }
}

// Chama a função para preencher os campos do formulário
callCookieLastUtm();
</script>

Sorry, should have clarified, since it’s JS issue I’d need the published pages where the JS runs- webflow.io pages are fine. I’d need also your homepage link and a link to a page where the form script is working how you want, so I can compare.

ok!

here is a page where the script works:

(https://www.octadesk.com/form-agendamento)

and the homepage where is not working

(https://octadesk-lp-1fa70c78c13d28f4289ba167211.webflow.io/)

I’m sharing the test link because we removed the form from the live version to prevent leads from running into this error.

Based on the working demo page I think we’re talking about this form-
And based on the script you shared, I suspect the main validation you’re looking for is that international phone validation.

If that’s correct, on the homepage, that corresponds to this form-
Which you can see is working in my screenshot.

The reason it’s not working on your homepage is that you’re using ID’s to reference the phone number field which is in this form [1], but you have another copy of the form [2] hidden [3][4] earlier on the page.

Your scripts are installing your validation there without errors, but you cannot see that form.

When you use display: none to hide that form, it’s still in the page. Instead, set that element to Visibility Hidden under settings.

wow, i can’t believe that was the issue after all! Thank you so much for your help!

1 Like