5

After regex is called cursor goes to end. So I tried that fix, that also did not work properly. How can that be fixed? My target: if field empty and digits is typed > cursor at end, if back to add or delete any digit > cursor at proper position(not at 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

2
  • you can test your fiddle to get sure that it is not working Commented Nov 12, 2015 at 15:12
  • I misinterpreted thinking you wanted at the end, I posted a new answer explaining hot to put the cursor in the right place Commented Nov 12, 2015 at 15:51

2 Answers 2

2

Set the selection range to "position" that you created, and if you include a "-" you increment the position, like that:

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);
});
Sign up to request clarification or add additional context in comments.

1 Comment

if I add another regex for example like jsfiddle.net/TeodorKolev/ku8bg0c9/3 how can I resolve it, cuz still jumps to end. Thanks
0

Try setSelectionRange().

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

I put 10000 for length as I don't think 10000 characters will ever be inputted. But you can set the length based on length of the input string.

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

1 Comment

yes but after I back to add for example number after 2nd it goes to end > which is wrong

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.