Auto Format Date & Phone Number (Elementor Pro)

July 10, 2023

In this Elementor Pro tutorial I will show you how to change the date and phone number format as a user is typing. This will be pulled off with JavaScript and no additional plugins.

Timestamps:

  • 0:00 Introduction
  • 0:39 Elementor Tutorial Begins

Date JavaScript Code:

				
					<script>
document.addEventListener('DOMContentLoaded', function() {
  const birthdayInput = document.getElementById('form-field-birthday');

  birthdayInput.addEventListener('input', formatBirthday);

  function formatBirthday() {
    let inputValue = birthdayInput.value;
    inputValue = inputValue.replace(/\D/g, ''); // Remove non-digit characters

    if (inputValue.length > 8) {
      inputValue = inputValue.slice(0, 8);
    }

    let formattedValue = '';

    if (inputValue.length > 4) {
      const day = inputValue.slice(0, 2);
      const month = inputValue.slice(2, 4);
      const year = inputValue.slice(4, 8);

      formattedValue = `${day}/${month}/${year}`;
    } else if (inputValue.length > 2) {
      const day = inputValue.slice(0, 2);
      const month = inputValue.slice(2, 4);

      formattedValue = `${day}/${month}`;
    } else {
      formattedValue = inputValue;
    }

    birthdayInput.value = formattedValue;
  }
});

</script>
				
			

Phone Number JavaScript Code:

				
					<script>
document.addEventListener('DOMContentLoaded', function() {
  const phoneNumberInput = document.getElementById('form-field-phone');

  phoneNumberInput.addEventListener('input', formatPhoneNumber);

  function formatPhoneNumber() {
    let inputValue = phoneNumberInput.value;
    inputValue = inputValue.replace(/\D/g, ''); // Remove non-digit characters

    if (inputValue.length > 10) {
      inputValue = inputValue.slice(0, 10);
    }

    let formattedValue = '';

    if (inputValue.length > 6) {
      const areaCode = inputValue.slice(0, 3);
      const prefix = inputValue.slice(3, 6);
      const lineNumber = inputValue.slice(6, 10);

      formattedValue = `${areaCode}-${prefix}-${lineNumber}`;
    } else if (inputValue.length > 3) {
      const areaCode = inputValue.slice(0, 3);
      const prefix = inputValue.slice(3, 6);

      formattedValue = `${areaCode}-${prefix}`;
    } else {
      formattedValue = inputValue;
    }

    phoneNumberInput.value = formattedValue;
  }
});

</script>
				
			

*Some of the links on this page are affiliate links, meaning we may receive a commission if you follow them. This allows us to continue providing free content and educational resources for you. Thank you for supporting our small business!

Share this post:

Facebook
Reddit
Twitter
Pinterest
LinkedIn
Email

More Free Resources