首页 文章

如何在输入时更改输入中的电话号码格式?

提问于
浏览
18

My CodePen: http://codepen.io/leongaban/pen/cyaAL

我有一个电话号码的输入字段,最多允许20个字符(国际号码) .

我也使用Masked input jQuery plugin by Josh Bush来格式化输入中的电话号码,使其成为'pretty' .

enter image description here

  • 我的问题是,当手机的数字为10位或更少时,它应该使用Masked输入格式 .

  • 但是,当电话号码长于10位时,应删除格式 .


这是我目前的:CodePen,手机是输入字段,我正在努力实现这一目标 . Work Phone是Mask input plugin的默认功能示例 .

How would you go about this problem?

jQuery for Cell Phone输入字段:

case '2':
    console.log('created phone input');
    $('.new_option').append(myphone);
    $('.added_mobilephone').mask('(999) 999-9999? 9');
    $('.added_mobilephone').keypress(function(event){

      if (this.value.trim().length > 10) {
        console.log('this.value = '+this.value.trim());
        console.log('greater then 10');
        $('.added_mobilephone').mask('99999999999999999999');
      }

      /*if (this.value.length < 9) {
        console.log(this.value);
        console.log('less then 10');
        $('.added_mobilephone').mask('(999) 999-9999? 9999999999');
      } else if (this.value.length > 9) {
        console.log(this.value);
        console.log('greater then 10');
        $('.added_mobilephone').mask('99999999999999999999');
      }*/
    });
    break;

7 回答

  • 22

    你需要注意,以便将来需要对控件应用多个蒙版的其他人想要探索这个inputmask plugin .

    它有更多的回调,设置和许多开箱即用的掩码类型(请务必查看扩展文件) . 您还可以为控件定义多个掩码,插件将尝试根据值应用适当的掩码 .

    Here is a fiddle演示以前的声明:

    $(window).load(function()
    {
       var phones = [{ "mask": "(###) ###-####"}, { "mask": "(###) ###-##############"}];
        $('#textbox').inputmask({ 
            mask: phones, 
            greedy: false, 
            definitions: { '#': { validator: "[0-9]", cardinality: 1}} });
    });
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.inputmask/3.1.62/jquery.inputmask.bundle.js"></script>
    <input type='text' id='textbox' />
    
  • 1
    $("input[name='phone']").keyup(function() {
        $(this).val($(this).val().replace(/^(\d{3})(\d{3})(\d)+$/, "($1)$2-$3"));
    });
    

    这肯定会起作用:)

  • 28

    这非常有用,我只添加了一些代码,以便在用户删除某些字符时使用它,我只选择输入数字和最大长度 . 这对我有用:)

    $(document).ready(function(){
      /***phone number format***/
      $(".phone-format").keypress(function (e) {
        if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
          return false;
        }
        var curchr = this.value.length;
        var curval = $(this).val();
        if (curchr == 3 && curval.indexOf("(") <= -1) {
          $(this).val("(" + curval + ")" + "-");
        } else if (curchr == 4 && curval.indexOf("(") > -1) {
          $(this).val(curval + ")-");
        } else if (curchr == 5 && curval.indexOf(")") > -1) {
          $(this).val(curval + "-");
        } else if (curchr == 9) {
          $(this).val(curval + "-");
          $(this).attr('maxlength', '14');
        }
      });
    });
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input class="phone-format"  type="text" placeholder="Phone Number">
    
  • 3

    在你的情况下

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/jasny-bootstrap/3.1.3/js/jasny-bootstrap.min.js"></script>
    
    <input type="text" class="form-control" data-mask="(999) 999-9999">
    

    使用jasny bootstrap插件

  • 0

    我尝试了一些非插件的答案,但不幸的是,在编辑电话号码时,它们有不良副作用 . 这是一个我最终创建的解决方案,它很简单,并且没有特殊的外部第三方lib依赖项:

    • 不需要任何插件 - >只需JS和JQuery

    • 自动过滤掉非数字(即噪音)

    • 在删除数字时,班次会保留电话号码

    • 维护格式/删除时不会中断

    • 如果没有任何改变,则什么也不做允许光标向左/向右移动以与其他使光标挂钩结束的解决方案进行更改

    CAVEAT:考虑的电话号码只是北美,我的情况很好,因为这被用于加拿大的当地社区足球注册 .

    $("input[name='phone_num']").keyup(function() {
      var val_old = $(this).val();
      var val = val_old.replace(/\D/g, '');
      var len = val.length;
      if (len >= 1)
        val = '(' + val.substring(0);
      if (len >= 3)
        val = val.substring(0, 4) + ') ' + val.substring(4);
      if (len >= 6)
        val = val.substring(0, 9) + '-' + val.substring(9);
      if (val != val_old)
        $(this).focus().val('').val(val);
    });
    
  • 15

    输入类型文本输入类型电话号码 . max-length,占位符使用jquery .

    // Used to format phone number and add placeholder and max-length
    function phoneFormatter() {
     $(' input[type="text"]').attr({ placeholder : '(___) ___-____' });
      $('input[tabindex="111"]').on('input', function() {
        var number = $(this).val().replace(/[^\d]/g, '')
        if (number.length == 7) {
          number = number.replace(/(\d{3})(\d{4})/, "$1-$2");
        } else if (number.length == 10) {
          number = number.replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3");
         
        }
        $(this).val(number)
        $('input[type="text"]').attr({ maxLength : 10 });
        
      });
    };
    
    $(phoneFormatter);
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input type="text" name="input_111[]" value="" tabindex="111">
    
  • 0

    上面的类似解决方案,但在此脚本中,格式正在应用,同时用户正在键入 . 在电话号码中添加掩码 - 巴西电话格式(00)?0000-0000 . 它对其他人也有帮助 .

    //Add mask (00) ?0000-0000 in the phone number - Brazil Format
        $('#iTel').on("keyup blur", function(e){
        	var v = $(this).val();
        	v = v.replace(/[^\d]/g,'');
        	if(v.length < 6){
        		v = v.replace(/(\d{2})/, '($1) ');
        	}else if(v.length < 10){
        		v = v.replace(/(\d{2})(\d{4})/, '($1) $2-');
        	}else if(v.length < 11){
        		v = v.replace(/(\d{2})(\d{4})(\d{4})/, '($1) $2-$3');				
        	}else {
        		v = v.replace(/(\d{2})(\d{5})(\d{4})/, '($1) $2-$3');
        	}
        $(this).val(v);		
           });
    
    <!DOCTYPE html>
         <html lang="en">
         <head>
           <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        </head>
        <body>
        <form method="post" id="cadForm" action="incluir.php">
        <div class="form-row">
         <div class="form-group col-md-12">
        	<label for="iTel" class="col-form-label">Phone</label>
        	<div class="input-group">
        	<span class="input-group-addon"><i class="fa fa-phone" aria-hidden="true"></i></span>
        	<input type="text" class="form-control" name="iTel" id="iTel" maxlength="15" placeholder="(xx) ?xxxx-xxxx..." pattern="[(][0-9]{2}[)][\s][0-9]{4,5}[-][0-9]{4}$" title="Please, type only number: (00) ?0000-0000">
        	</div>			
        </div>
          </body>
         </html>
    

相关问题