在提供电话号码时,如何在特定数字之间添加空间



我有输入字段,用户提供他的电话号码,例如:

<label for="phone" class="first-col">Phone No.:</label>
<input type="text" id="phone" />
<span class="form-hint">Proper format "8 600 00 000"</span>

我需要在用户键入编号以下时进行以下操作:

861234567

它在以下内容中自动添加空格:

8 612 34 567

有什么想法我该如何实现?使用 java脚本或与 css 一起使用?或者,也许有办法通过 html 实现它?我什么也没发现。

这是我在纯JavaScript中的解决方案

document.getElementById('phone').addEventListener("keyup", function(){
   txt=this.value;
   if (txt.length==1 || txt.length==5 || txt.length==8)
    this.value=this.value+" ";
  
});
<input type="text" id="phone"/>

尝试此

$("input[name='phone']").keyup(function() {
var curchr = this.value.length;
var curval = $(this).val();
if (curchr == 1) {
    $("input[name='phone']").val("" + curval + "" + " ");
} else if (curchr == 4) {
    $("input[name='phone']").val(curval + " ");
}else if (curchr == 8) { 
    $("input[name='phone']").val(curval + " ");
}

}(;

最新更新