Add dash in auto complete phone number

后端 未结 3 1934
一整个雨季
一整个雨季 2020-12-30 11:04

Question:

Is it possible to automatically add a dash \"-\" in auto complete?

Let say I have a phone number field and if someone will type their phone number

相关标签:
3条回答
  • 2020-12-30 11:14

    The above answers were fine, but I faced some issue while copy paste that is entry of other character other then number so I used:

      $('#help_number').keyup(function(){
        $(this).val($(this).val().match(/\d+/g).join("").replace(/(\d{3})\-?(\d{3})\-?(\d{4})/,'$1-$2-$3'))
      });
    

    Example:

    str="34%^gd 5-67 6-6ds897"
    
    str.match(/\d+/g).join("")
    

    output is : >> "3456766897"

    str.match(/\d+/g).join("").replace(/(\d{3})\-?(\d{3})\-?(\d{4})/,'$1-$2-$3')
    

    output is : 345-676-6897

    0 讨论(0)
  • 2020-12-30 11:23

    You can try this code.

    $(function () {
    
        $('#txtnumber').keydown(function (e) {
           var key = e.charCode || e.keyCode || 0;
           $text = $(this); 
           if (key !== 8 && key !== 9) {
               if ($text.val().length === 3) {
                   $text.val($text.val() + '-');
               }
               if ($text.val().length === 7) {
                   $text.val($text.val() + '-');
               }
    
           }
    
           return (key == 8 || key == 9 || key == 46 || (key >= 48 && key <= 57) || (key >= 96 && key <= 105));
       })
    });
    

    HTML input

    <input id="txtnumber"   type="text" maxlength="12" placeholder="xxx-xxx-xxxx" />
    

    You can also see in jsfiddle

    https://jsfiddle.net/karthikjsf/38vdpj4f/

    0 讨论(0)
  • 2020-12-30 11:30
    $('#phone-number-field').keyup(function(){
        $(this).val($(this).val().replace(/(\d{3})\-?(\d{3})\-?(\d{4})/,'$1-$2-$3'))
    });
    
    0 讨论(0)
提交回复
热议问题