Format Phone Numbers onblur

by Nibin George

HTML

<input type="text" id="editphone" name="test" />

JavaScript

$('#editphone').keypress(function(e){ 	
        var phone = $(this).attr('value');
        var $this = $(this);
    if (event.keyCode < 48 || event.keyCode > 57 ) {
        return false
    }
    if(e.keyCode!=8){ 	
            if(phone.length==3 || phone.length==7){				
                $('#editphone').attr('value',phone+'-');			
            }
            if(phone.length==4 || phone.length==8){				
                var hiphen=phone.substr(phone.length-1);
                if(hiphen != '-'){
                    var phoneNum=phone.substr(0,phone.length-1)+'-'+phone.substr(phone.length-1);
                    $('#editphone').attr('value',phoneNum);
                }			
            }	
        }
    });