I’m terrible at JS regular expressions and I’m counting on an intelligent being to help me accomplish what should be a trivial task.
Onblur, I want a text field of 10 numbers ‘1234567890’ to be formatted as 123/456/7890 using JS.
And Onfocus, it should revert to the number ‘1234567890’ without slashes.
That’s it. Hope you can help!
Update: I arrived at a solution, so I’ll post the answer below for the sake of future searchers.
HTML:
<input id="PhoneNumber" type="text" maxlength="10"
onblur="PhoneNumberOnBlur(this)"
onfocus="PhoneNumberOnFocus(this)"/>
Javascript:
function PhoneNumberOnBlur(el) { el.value = el.value.replace(/(\d{3})(\d{3})(\d{4})/, "$1/$2/$3"); }
function PhoneNumberOnFocus(el) { el.value = el.value.replace(/\//g, "") }
To add slashes:
to remove them:
For something more robust, I’d recommend the Masked Input plugin:
http://digitalbush.com/projects/masked-input-plugin/