Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Input cursor position jumps to end with ng-change()

I have an instance where I'm replacing the value of ngModel through ngChange. The cursor jumps to the end of the input field after each change (assuming because I'm assigning the result to the same $scope variable.)
I'd like to know how I can prevent this behavior?

  $scope.compute1 = 0;
  $scope.compute2 = 10;

  $scope.math = function() {
    $scope.compute1 = parseInt($scope.compute1);
    $scope.compute2 = parseInt($scope.compute2);

    $scope.compute1 = parseInt($scope.compute1);
  };

fiddle

Example of problem: if a user types in 1000. It's fine. But then if they want to go back and change the number to 156000 by just adding the 5 and 6, the 6 would actually be appended to the end: 15006.

like image 795
EnigmaRM Avatar asked Dec 07 '25 00:12

EnigmaRM


1 Answers

The cursor goes to the end because we modify data by using parseInt.

I suggest you to store the caret position before and then when you're done doing things, set it back.

This example might help you: Link

like image 89
Maxim Shoustin Avatar answered Dec 08 '25 16:12

Maxim Shoustin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!