Stop cursor from jumping to end of input field in javascript replace

后端 未结 3 962
盖世英雄少女心
盖世英雄少女心 2020-11-27 05:29

I\'m using a regular expression to strip invalid characters out of an text input area in javascript (running in IE). I run the replace function on every keyup event. However

3条回答
  •  余生分开走
    2020-11-27 06:11

    In addition to gilly3's answer, I thought someone might find it useful to see an actual code snippet.

    In the example below, the selectionStart property is retrieved from the input element prior to the JavaScript string manipulation. Then selectionStart is set back to the initial position after the manipulation.

    Depending on what you're trying to achieve, you could also access selectionEnd in place of selectionStart, and set a range: setSelectionRange(start, end).

    document.getElementById('target').addEventListener('input', function (e) {
      var target = e.target,
          position = target.selectionStart; // Capture initial position
      
      target.value = target.value.replace(/\s/g, '');  // This triggers the cursor to move.
      
      target.selectionEnd = position;    // Set the cursor back to the initial position.
    });

    The method .replace() will move the cursor's position, but you won't notice this.

提交回复
热议问题