【问题标题】:How to allow only 11 numbers in input filed如何在输入字段中只允许 11 个数字
【发布时间】:2022-11-22 12:44:03
【问题描述】:

我有一个输入字段,我只想允许用户输入 11 个数字,在 11 个数字之后,他只能输入破折号 (-),然后是第二个 11 位数字。我是初学者请帮助我。我怎样才能做到这一点? 在破折号之后 - 和数字是可选的。我正在使用 jquery 并且正在尝试但没有得到任何东西。请帮我。提前致谢。

<input type="text" class="form-control" placeholder="e.g 03xxxxxxxxx-03xxxxxxxxx" id="contact" oninput="update()">

【问题讨论】:

    标签: jquery


    【解决方案1】:

    您可以使用 inputmask 来创建所需的结果。

    $('#contact').inputmask("99999999999-99999999999", {
      "placeholder": "03xxxxxxxxx-03xxxxxxxxx",
      onincomplete: function() {
        $(this).val('');
      }
    });
    

    这将根据您的模式生成占位符和“设置”允许的最大字符数。

    演示

    $('#contact').inputmask("99999999999-99999999999", {
      "placeholder": "03xxxxxxxxx-03xxxxxxxxx",
      onincomplete: function() {
        $(this).val('');
      }
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/3/jquery.inputmask.bundle.js"></script>
    
    <input type="text" class="form-control" id="contact"  >

    【讨论】:

    • 实际上,问题在于破折号和破折号后的数字是可选的。那么我该如何实现呢?通过使用掩码,因为如果你使用掩码,你已经写完了
    猜你喜欢
    • 2014-09-14
    • 2018-03-06
    • 1970-01-01
    • 2019-02-10
    • 1970-01-01
    • 1970-01-01
    • 2018-11-27
    • 2020-03-23
    • 1970-01-01
    相关资源
    最近更新 更多