【问题标题】:backspace regex gets returned to end of regex array value on input退格正则表达式在输入时返回到正则表达式数组值的末尾
【发布时间】:2017-03-06 17:22:08
【问题描述】:

我有一个输入,此输入的限制为 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);

【问题讨论】:

    标签: javascript jquery arrays regex


    【解决方案1】:

    记住位置,完成操作后更新位置。

    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();
      }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-25
      • 1970-01-01
      相关资源
      最近更新 更多