【问题标题】:how to format input value same time of key press如何在按键的同时格式化输入值
【发布时间】:2018-12-18 09:00:46
【问题描述】:

我想按照以下格式排列我的输入(电话号码)值

<input type="text" value="123-456-7890">

如果输入 1234567890,它将设置为 123-456-7890

【问题讨论】:

  • 当输入了一定数量的数字时,您可以使用更改侦听器并附加连字符。
  • 您想获取该格式的值,或者您希望字段内的数字应替换为该格式?
  • 感谢您对 Jaybird 的回复,但我不想使用插件
  • 你好 Mayank,我想要该字段内的数字并以该格式替换?

标签: javascript jquery html


【解决方案1】:

$("input").keyup(function() {
  var length = 0;
  length = $('#txtval').val().length;
  if (length == 3 || length == 7) {
    $('#txtval').val($('#txtval').val().concat('-'));
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Phone: <input type="text" id="txtval" value="" placeholder="Enter your Phone" />

【讨论】:

  • 代码应该总是带有解释。请解释上面的代码。
【解决方案2】:
var $phone=1234567890
$phone.replace(/(\d{3})(\d{3})(\d{4})/, "$1-$2-$3");

输出:

123-456-7890

编辑: 用 keyup 更新了 JsFiddle

在 div 中输出 - 电话号码硬编码
http://jsfiddle.net/smileyface/mu95g83n/

在 div 中输出
http://jsfiddle.net/smileyface/mu95g83n/17/

在文本框内输出
http://jsfiddle.net/smileyface/mu95g83n/20/

$(document).ready(function() { //Run when document is ready (page loaded)
  $('#txtval').keyup(function count() { //on every key up inside textbox
    var $input = this.value;

    if ($input.length == 3) {
      $('#txtval').val($input + "-"); //add hiphen to input after 3 letters
    }
    if ($input.length == 7) {
      $input = $input.replace(/(\d{3})(\d{3})/, "$1-$2")
      $('#txtval').val($input + "-"); //add hiphen after 7 letters
    }
    if ($input.length == 11) {
      $input = $input.replace(/(\d{3})(\d{3})(\d{4})/, "$1-$2-$3")
      $('#txtval').val($input); //show phone number as expected
    }
  });


});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Enter Phone# : <input type="text" id="txtval" maxlength="12" />

【讨论】:

  • 如果您想对此进行任何更改,请告诉我
猜你喜欢
  • 1970-01-01
  • 2011-05-02
  • 2023-03-17
  • 1970-01-01
  • 1970-01-01
  • 2013-11-22
  • 1970-01-01
  • 2016-02-25
  • 1970-01-01
相关资源
最近更新 更多