Javascript: 'Issue?' on updating user input in thousands figure in a text box

I am checking at this code found on a one question asked here regarding on adding of commas while user was typing a number.

$('input.number').keyup(function(event) {
  // skip for arrow keys
  if(event.which >= 37 && event.which <= 40) return;
  // format number
  $(this).val(function(index, value) {
    return value
    .replace(/\D/g, "")
    .replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  });
});

~ @macek

Arrow key skip is working good and the rest. The only problem is when you input in between or update the digits let say I enter

"1234789"

notice that I do not have the numbers 5 and 6 in between to complete the numbers 1 to 9 now when I tried to update and enter 5 and 6 the result is "123,457,896". The reason why the 6 go to last part was the cursor moves automatically in the last part in the second key pressed.

Is there any way to make the cursor stay in its current position? I am not certain if this was because of the keyup function Also what I am trying to solve is how to make (CTRL + A) Copy All text work?

By the way I am not used in regex yet, but a deeper explanation of regex given in the example above is a plus :)

Answers 1

  • EDIT : Added CTRL-Key possible AND SHIFT selection

    Here is how :

    $('input.number').keyup(function(event) {
      // skip for arrow keys
      if(event.which >= 37 && event.which <= 40) return;
      if (event.ctrlKey) return;
      if (event.which == 17) return; // CTRL Key
      if (event.which == 16) return; // Shift Key
    
      //Get old values
      var oldPosition = $(this)[0].selectionStart;
      var oldLength = $(this).val().length;
    
      // format number
      $(this).val(function(index, value) {
        return value
        .replace(/\D/g, "")
        .replace(/\B(?=(\d{3})+(?!\d))/g, ",");
      });
    
      //Set caret position
      var offset = $(this).val().length - oldLength;
      $(this)[0].selectionStart = oldPosition + offset ;
      $(this)[0].selectionEnd = oldPosition + offset ;
    });
    

Related Articles