Set input cursor to correct position after javascript regular expression

After calling the regular expression, the cursor comes to an end. So I tried to fix it, which didn't work either. How can this be fixed? My goal: if the field is empty and the numbers are printed> the cursor is at the end, if you return to add or remove any digit> the cursor is in the right position (not at the end)

document.getElementById('target').addEventListener('input', function (e) {
  var target = e.target,
      position = target.selectionStart; // Capture initial position

  target.value = target.value.replace(/\B(?=(\d{3})+(?!\d))/g, "-");// This triggers the cursor to move.

  target.selectionEnd = position;    // Set the cursor back to the initial position.
});

Fiddle

+4
source share
2 answers

Set the selection range to the "position" that you created, and if you added a "-", you increase the position, for example:

document.getElementById('target').addEventListener('input', function (e) {
  var target = e.target,
  position = target.selectionStart; // Capture initial position

  var old = target.value;
  target.value = target.value.replace(/\B(?=(\d{3})+(?!\d))/g, "-");

  if(old != target.value)
    position++;
  target.setSelectionRange(position, position);
});
+2
source

Give it a try setSelectionRange().

: ** http://jsfiddle.net/ku8bg0c9/2/

10000 , , 10000 . , .

document.getElementById('target').addEventListener('input', function (e) {
    var target = e.target,
        position = target.selectionStart; // Capture initial position

    target.value = target.value.replace(/\B(?=(\d{3})+(?!\d))/g, "-"); // This triggers the cursor to move.

    target.selectionEnd = position; // Set the cursor back to the initial position.

    target.setSelectionRange(10000, 10000);
});
0

Source: https://habr.com/ru/post/1615598/


All Articles