如何同时格式化输入值

时间:2018-12-18 09:00:47

标签: javascript jquery html

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

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

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

2 个答案:

答案 0 :(得分: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" />

答案 1 :(得分:2)

$("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" />