Dynamically Format User Inputs While They Are Typing
Learn how to format user input fields while users are typing using Corvid (a.k.a. Wix Code).
This example shows you how to create user input fields which dynamically formats the users input while they are typing. Try the example below for phone numbers of the format (xxx) xxx-xxxx. Only numbers are allowed to be entered, with the brackets and dash being automatically applied. You can adapt the code to any other format desired.
#iptPhone
Try it!
Add an onClick and an onKeyPress event listener to the #iptPhone field. The iptPhone_click function adds the first bracket of the phone number format as soon as the input field is clicked. The iptPhone_keyPress function allows 10 milliseconds for the users input to register, and then calls the formatPhoneInput function to perform the rest of the phone number formatting.
The formatPhoneInput function first finds the latest keystroke pressed, except if it was a backspace, and stores this value in newNum. The backspace variable looks at whether the value stored in #iptPhone has become smaller in length to determine whether a backspace was used. The first if-else statement builds the buildNumber variable on the numeric values entered by the user. It also reduces this value if the user has backspaced any digits. Non-numbers are ignored. Following this, a sequence of variables are created to separate and store the digits in each part of the phone number for ease of reassembly as the final formatted phone number. The second set of if-else functions constructs the formatted phone number from the numeric components created in the previous step.
Page Code