Javascript 提供电话号码时如何在特定数字之间添加空格
我有一个输入字段,用户在其中提供他的电话号码,如下所示:Javascript 提供电话号码时如何在特定数字之间添加空格,javascript,jquery,html,css,Javascript,Jquery,Html,Css,我有一个输入字段,用户在其中提供他的电话号码,如下所示: <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 有
<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=该值;
如果(txt.length==1 | | txt.length==5 | | txt.length==8)
this.value=this.value+“”;
});代码>
试试这个
$("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 + " ");
}
})) 它会自动在以下位置添加空格(1位之后、4位之后、6位之后):8 612 34 567
。你的句子和号码不匹配。我更愿意提供三个/四个框以及连字符来输入电话号码。屏蔽是你应该在谷歌上搜索的关键字。