I have an input text field with a maxlength of 10. The field is for Australian phone numbers (10 digits). Phone numbers are generally split up into the following syntax
12 12345678
If someone copies the above and pastes that into my input field, it obviously leaves the last digit out and keeps the space.
Is there a way to remove any spaces right before it is pasted into the input box? Or is there another work around?
Thanks in advance.
JavaScript String trim() The trim() method removes whitespace from both sides of a string.
For removing extra spaces, you can use the predefined JavaScript methods, including replace() method, split() method, or trim() method. The trim() method removes the spaces at the start of the string, while the replace() method removes extra spaces between words. The split() method removes all the spaces between words.
This should work for you:
HTML
<input type="text" id="phone" maxlength="10" />
JavaScript
var phone = document.getElementById('phone'),
cleanPhoneNumber;
cleanPhoneNumber= function(e)
{
e.preventDefault();
var pastedText = '';
if (e.clipboardData && e.clipboardData.getData)
{// Standards Compliant FIRST!
pastedText = e.clipboardData.getData('text/plain');
}
else if (window.clipboardData && window.clipboardData.getData)
{// IE
pastedText = window.clipboardData.getData('Text');
}
this.value = pastedText.replace(/\D/g, '');
};
phone.onpaste = cleanPhoneNumber;
Fiddle: http://jsfiddle.net/y6TYp/6/
Update nnnnnn had a great point regarding Australian phone numbers, updating replace regex.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With