I need to have a phone number be formatted on the fly into a 10 digit number - remove ALL spaces, dashes, dots, etc.
EX: (123) 321-1234 / 123-321-1234 becomes 1233211234
I've seen examples of doing the opposite, but since I'm new to Javascript, I don't know how to do it.
Ideally, formatting should while the number is being entered into text field, or when a Submit button is pressed.
PS - I only know HTML, so please provide code for both and tags.
Very much appreciate your help!
You can use a regex to remove all non-digits from the textbox's value. Here's an example:
<input type="text" id="text1" />
With this JS:
function addEvent(element, eventName, callback) {
if (element.addEventListener) {
element.addEventListener(eventName, callback, false);
} else if (element.attachEvent) {
element.attachEvent("on" + eventName, callback);
}
}
addEvent(window, "load", function () {
addEvent(document.getElementById("text1"), "change", function () {
var tel = this.value;
tel = tel.replace(/\D+/g, "");
this.value = tel;
});
});
DEMO: http://jsfiddle.net/6vC3x/
The replacing happens when the value of the textbox is changed (by user input) and the textbox is blurred (unselected).
The whole addEvent
function stuff is just to hopefully reliably add event handlers to an element across browsers consistently.