Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onChange is not called when typing `e` in number input in React and Vanilla Javascript

I found a strange behaviour when working with input fields with type="number" in React. I have a really simple React component with one controlled number input field and as e.target.value is always a string, I am parsing it to make it a number.

function App() {
  const [value, setValue] = React.useState("");

  const handleInputChange = (e) => {
    const input = e.target.value;
    console.log(input);
    const parsedValue = parseInt(input, 10);
    console.log(parsedValue);
    setValue(isNaN(parsedValue) ? input : parsedValue);
  };
  return (
      <form>
        <input
          type="number"
          min={1}
          max={100}
          value={value}
          pattern="\d+"
          onChange={handleInputChange}
        />
      </form>
  );
}

The handleInputChange function is called every time I enter a new value input, but it is not called when I type characters e, '+', or .. For the +, ., and -, I understand that we expect some digit after that so calling onChange doesn't make much sense but for the e, it should have called onChange.

I tried to simulate the same behaviour with vanilla javascript but there change event is only called if I increase/decrease the number using arrow keys. Here is the [codepen example for the same][1]

Can someone explain this behaviour and how can I detect typing e in number input?

Edit: I think there is some confusion with this question. I want to understand two things about change event behaviour for number input fields.

  1. Why React doesn't call onChange when I type e, '+', '-', and '.' ?
  2. Why change event is not called when I type some value in input in Vanilla Javascript? [1]: https://codepen.io/aditya81070/pen/WNjoLao
like image 707
aditya81070 Avatar asked Oct 27 '25 22:10

aditya81070


1 Answers

Any text ending with e is not a number. It is like 1e3 or 2e4. So if your number is ending with 1e, it is not valid. Javascript is preventing you from doing so that is why both in your native code and in react, although the onChange(/onchange) is triggered the e.target.value is "". So you can not make use of it.

like image 138
Tushar Shahi Avatar answered Oct 29 '25 13:10

Tushar Shahi