How To Add A Hyphen

You might also like

You are on page 1of 1

Automatically add hyphen in phone number in HTML

using Javascript
I tried to research the answer to this question but I'm lost with when I typing the numbers
from the numeric keypad. I am trying to make a one hyphen that automatically puts a
hyphen in the phone number [xxx-xxx-xxxx]. I've solved that with adding my own
validations in the findings.
1. Write this javascript code in your HTML page define a function.
<script type="text/javascript">
function phonewithhypen(event, phone){
var phonelength = phone.value.length;
var key = keyValue(event);
if((key>47 && key<58)||(key>=96 && key<106))
{
if(phonelength ==3 )
phone.value= phone.value+'-'
else if(phonelength ==7 )
phone.value= phone.value+'-'
else
phone.value= phone.value;
}
else{
phone.value = phone.value.replace(/[^0-9-]/,'')
phone.value = phone.value.replace('--','-')
}
}
function keyValue (event) {
var code;
if (!event)
var event = window.event;
if (event.keyCode) code = event.keyCode;
else if (event.which) code = event.which;
return code
//
return String.fromCharCode(code);
}
</script>
2.Write HTML code for displaying a phonenumber textbox and and to call
javascript function
<input name="phone" type="text" id="phone" onkeydown=" phonewithhypen
(event,this)" onkeyup=" phonewithhypen (event,this)"
maxlength="12">

You might also like