0

I'm new to angularJS and want to rewrite an input field when the user presses a certain character. For example, if the user enters "aab", when the "b" is pressed I want to replace the entire field with just "y".

Using ng-keypress partly works, but leaves "yb" instead of just "y". The full example code is below. To test it enter "aab".

<html ng-app="testApp">
<body ng-controller="testCtrl as ctrl">

<form name="testForm">
<input
  type="text"
  ng-keypress="ctrl.keyPressFunc($event)"
  name="testName"
  ng-model="ctrl.testValue"
  required
>
<br/>
ctrl.testValue: {{ctrl.testValue}} <br/>
ctrl.eventa: {{ctrl.eventa}} <br/>
<p/>
ctrl.eventa.charCode: {{ctrl.eventa.charCode}} <br/>
ctrl.eventa.keyCode: {{ctrl.eventa.keyCode}} <br/>
ctrl.eventa.shiftKey: {{ctrl.eventa.shiftKey}} <br/>
ctrl.eventa.altKey: {{ctrl.eventa.altKey}} <br/>
ctrl.eventa.ctrlKey: {{ctrl.eventa.ctrlKey}} <br/>
</form>

<script
  src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.11/angular.js">
</script>

<script type="text/javascript">
  angular.module('testApp', [])
    .controller('testCtrl', [function () {
      var self = this;
      self.eventa = null;
      self.testValue = "x";       // initialize the input field

      // When the user presses 'b', change the entire testValue to "y".
      self.keyPressFunc = function(eventa) {
        self.eventa = eventa;
        if (eventa.charCode == 98) {   // if 'b'
          self.testValue = "y";
        }
      };

    }]);
</script>
</body>
</html>

How can I get angularJS to show "y" and not "yb"? Many thanks!

1 Answer 1

1

Use preventDefault when 'b' was pressed.

self.keyPressFunc = function(eventa) {
    self.eventa = eventa;
    if (eventa.charCode == 98) {   // if 'b'
      self.testValue = "y";
      eventa.preventDefault();
    }
};
Sign up to request clarification or add additional context in comments.

Comments

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.