我用过
phone.addEventListener("keyup", function(){
txt=this.value;
if (txt.length==3 || txt.length==7)
this.value=this.value+" ";
});
但此代码仅适用于输入类型的文本,问题是输入的长度不考虑为 10。
有没有办法,显示时带空格,长度必须10,带类型号,后台保存时不带空格?
最佳答案
示例解决方案使用 pattern
输入类型和简单的正则表达式,确保只有数字、正确的间距,并且只向服务器提交没有空格的数字。
如果用户自己输入空格,您的代码确实会崩溃,因此增强了 JavaScript 以确保格式正确。
- 通过防止默认行为(忽略击键)忽略空格输入和任何超过 12 个字符的输入:
if ((txt.length == 12 || e.which == 32) & e.which !== 8) e.preventDefault();
(字面意思是“如果 12 个字符或按键是空格键且按键不是退格键”则忽略按键)
- 自动添加空格(就像您的代码所做的那样):
if ((txt.length == 3 || txt.length == 7) && e.which !== 8)...
注意:在这两种情况下,如果按下退格键,则允许该键工作(键码 8)。
- 提交表单后,删除“电话”输入中的所有空格,以便服务器仅接收号码。
document.getElementById("phone").addEventListener("keydown", function(e) {
const txt = this.value;
// prevent more than 12 characters, ignore the spacebar, allow the backspace
if ((txt.length == 12 || e.which == 32) & e.which !== 8) e.preventDefault();
// add spaces after 3 & 7 characters, allow the backspace
if ((txt.length == 3 || txt.length == 7) && e.which !== 8)
this.value = this.value + " ";
});
// when the form is submitted, remove the spaces
document.forms[0].addEventListener("submit", e => {
e.preventDefault();
const phone = e.target.elements["phone"];
phone.value = phone.value.replaceAll(" ", "");
console.log(phone.value);
//e.submit();
});
<form>
<input id="phone" name="phone" type="pattern" placeholder="### ### ####" pattern="[\d]{3} [\d]{3} [\d]{4}">
<input type="submit">
</form>
关于javascript - 如何在输入中的数字之间留出空间以供显示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69211311/