html - 如何在html5的TextBox中自动在4位数字后插入连字符“-”?
问题描述
我已经在 html5 的输入字段中进行了验证,以获得这种格式 03xx-xxxxxxx。
pattern="03\d{2}-\d{7}"
现在我想在第四位之后自动添加这个连字符。怎么做?
解决方案
我必须建议您不要进行这种类型的输入编辑,因为当您需要编辑错别字时通常会令人沮丧。
我也不知道与可访问性相关的问题。
输入模式只检查提交的数据,所以它不是你要找的。
也就是说,这是 JS 中一种可能的解决方案:
// select the input element
var i = document.querySelector('input.hyphen');
// number of charatcers before the hyphen
var n = 4;
// run this function everytime the user release a key
i.addEventListener('keyup', function (event) {
// text cleared of all dashes
var t = i.value.replace(/-/g, '');
// save the carret position
var s = i.selectionStart;
// beguining string with n digits
var b = t.substr(0, n);
// end string with what's left (maxLength)
var e = t.substr(n);
// if there are more then n digits
if (e.length) {
// join then with a dash
i.value = [b, e].join('-');
// if the caret was before the dash put it back to the saved position
if (s <= n) i.setSelectionRange(s, s);
// if the caret was next to the dash put it after
if (s == n+1) i.setSelectionRange(s+1, s+1);
// if there's no end string then no need for dashes, just show the beguining
} else i.value = b;
});
<input class="hyphen" placeholder="0000-0000000" maxlength="12">
推荐阅读
- c++ - 无法使 opengl 纹理正常工作
- python-3.x - 将函数聚合到熊猫 groupby
- android - 如何将 id 从回收站视图传递到片段?
- javascript - 如何设置和使用工具提示?
- python-3.x - 更新熊猫数据框列表中的列
- vue.js - Vue 2 / Vue CLI 3:创建异步单文件组件
- java - 使用最新版本的 jdbc 连接器连接到 1.8 HyperSQL 数据库
- python - 编程面试要素中的死锁问题 19.5
- typescript - 找不到 Firebase 功能的 Typescript 声明
- c - 在 C 中填充二维 int 数组的最简单方法