mellis481
mellis481

Reputation: 4158

Suppressing keypress in onKeyPress, but onChange still fires

I have the following function which I've tied to the onKeyPress event of my ReactJS component:

onKeyPress(e) {
  if (!isNumeric(e.key) && e.key !== '.') {
    return false;
  }
}

This executes properly in that if the input is not numeric (eg. "b"), it will return false. The issue, though, is that the onChange() event linked to the control is still firing. I would expect that if you suppress the keyboard input, nothing will change and the onChange event won't fire. That does not appear to be happening.

Upvotes: 0

Views: 965

Answers (2)

Isaac
Isaac

Reputation: 12874

Just an extension to the number provided by @Joel

onKeyPress(e) {
  if (!isNumeric(e.key) && e.key !== '.') {
    e.preventDefault();
    //return false; Not needed
  }
}

You only need e.preventDefault(), return false can be excluded

Upvotes: 2

Joel Worsham
Joel Worsham

Reputation: 1150

You need to use preventDefault() on the event as to stop default event bindings. Modify your code to this for the fix:

onKeyPress(e) {
  if (!isNumeric(e.key) && e.key !== '.') {
    e.preventDefault();
    return false;
  }
}

Upvotes: 1

Related Questions