Issue on jQuery to Customize a Phone Filed Input Box

Issue on jQuery to Customize a Phone Filed Input Box

I am trying to use jQuery to customize a a text input box to accept phone in North america format like

 (555)-555-5555

I tried to use this at This Demo

  • var field = $('#phone');
    1. var fieldval = $('#phone').val();
    2.     var length,
    3.     var pattern = [3,6]
    4.     var maxlength = 11;

    5. field.onkeydown = function(event) {
    6.     // Length without hyphen
    7.     length = fieldval.replace("-", "").length;

    8.     if(pattern.indexOf(length) != -1) {
    9.         fieldval = field.value + '-';
    10.     }
    11.     if(fieldval.length > maxlength) {
    12.         fieldval = fieldval.substring(0, maxlength);
    13.     }
    14. }

    but it is not working! Technically what I need to do is loading adding () and - whan they meet the specified pathern?

    Thanks