Javascript Phone number auto convert is not working
<p>I have some javascript code like below</p>

<pre><code>function mask(eventVal,val){
    var len = val.value.length;
    var key = whichKey(eventVal);
    if(key&gt;47 &amp;&amp; key&lt;58)
    {   
        if( len==0 )val.value=val.value+'('
        else if( len==4 )val.value=val.value+') '
        else if(len==9 )val.value=val.value+'-'
        else val.value=val.value;
    }
    else{
        val.value = val.value.replace(/[^0-9-]/,'')
        val.value = val.value.replace('--','-')
    }
}

function whichKey(eventVal) {
    var code;
    if (!eventVal) var eventVal = window.event;
    if (eventVal.keyCode) code = eventVal.keyCode;
    else if (eventVal.which) code = eventVal.which;
    return code;
}
</code></pre>

<p>HTML</p>

<pre><code>&lt;input type="text" name="PhoneNumber" id="PhoneNumber" value="" onkeydown="mask(event,this)"/&gt;
</code></pre>

<p>It is working fine when I am typing phone number like 1234567890 is automatically converting into (123) 456-7890 when I am trying to remove value like remove 0 from the end then formatting is getting ruined completely. like 123) 456-789 and even it is getting ruined when I am click any other place. Can Any one help me to fix it? </p>
