javascript - 退格正则表达式返回到输入的正则表达式数组值的末尾

标签 javascript jquery arrays regex

我有一个输入,并且该输入的限制为 10。如果用户要删除或退格数字数组中间的数字之一,则光标或退格线现在位于数组的末尾,而不是比用户第一次选择要放置退格键的位置。我希望这样当用户选择这个数字数组并想要删除中间的两个数字时,他们可以这样做,而无需退格光标跳转到数字数组的末尾。 jsfiddle

HTML

<div>
<input type="text" id="test" name="test" style="width: 210px;" maxlength="10" />
</div>

JS

var y =  function (e) {
            var x = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
            e.target.value = !x[2] ? x[1] : x[1] + x[2] + (x[3] ? x[3] : '');
            var last = x[3];
            };    
            document.getElementById('test').addEventListener('input', y);

最佳答案

只需记住位置,然后在完成操作后更新位置。

Working Demo link

var y = function(e) {    
  var target = e.target;    
  var x = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
  var value = !x[2] ? x[1] : x[1] + x[2] + (x[3] ? x[3] : '');

  if (value === e.target.value) {
    return;
  }

  var position = target.selectionStart;
  e.target.value = value;      
  target.selectionEnd = position; // set the cursor on desired position.
};

document.getElementById('test').addEventListener('input', y);

//In order to avoid jumb behaviour when press non-numeric like a-z
document.getElementById('test').addEventListener('keypress', function(e) {
  if (e.which < 48 || e.which > 57) {
    e.preventDefault();
  }
});

关于javascript - 退格正则表达式返回到输入的正则表达式数组值的末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42631780/

相关文章:

javascript - AJAX : 301/302 header redirection (cross-domain) failing in some Webkit browsers

javascript - 从另一个 javascript webresource 调用 javascript 函数

javascript - 使用 Bootstrap 设置我的导航栏事件链接

javascript - 在单选按钮上使用 jQuery live 方法

javascript - 通过脚本比较 google 表格中的 A 列。当匹配正确时,然后在两侧粘贴偏移值

php - 无法将数组插入 MySQL

python - 在python中存储大量 bool 数据

javascript - 在 HandleBars JS 中处理 HTML 转义值

javascript - 使用javascript在页面加载时放大div

javascript - 如何在不丢失数据的情况下将 POST 正文数据传递到另一条路线?