3

The example below is number input which if contains "e" character will return "" empty string when accessed with JavaScript.

const input = document.querySelector('input');
input.oninput = (e) => console.log(e.target.value)
<input type="number">

Can you please explain the magic behind and possible way to prevent that from happening.

P.S: I am investigating the possibility to have input that will allow only [0-9] numbers on keyboard input/paste and will appreciate any suggestion on this topic :-)

volna
  • 2,452
  • 4
  • 25
  • 61
  • 1
    `e` and `E` are valid floating point notation and therefore allowed in numeric inputs. E.g. `3.14e2`. If you absolutely must forbid them, then you'll need to weed them out yourself – j08691 Jan 24 '20 at 21:47
  • @j08691 I was trying to weed before and ended up with the exact solution as Ritesh Khandekar suggests below, but replacing whole input value with an empty string doesn't seem like a nice UX, that's why wonder if there is a workaround it. – volna Jan 25 '20 at 05:36
  • It happens with `input[type='number']` when the inputted number is not complete (i.e. invalid). For example, when `1e` is pasted then `e.target.value` contains the empty string, but when `1e2` is pasted then `e.target.value` contains `1e2`. It happens with all events (oninput, onchange, onkeydown, onkeyup, onkeypress) and it looks like this is general browser behavior that can't be changed. – Mihail H. May 18 '22 at 13:31
  • The only exception I know is the `onpaste` event (`e.clipboardData.getData('text')` contains `1e` not empty string), but it's not easy to use in this case and doesn't cover all cases. – Mihail H. May 18 '22 at 13:51
  • Just try with `e.target.valueAsNumber` – Aruna Warnasooriya Jul 11 '23 at 04:58

2 Answers2

3

e stands for exponential, it is a valid character for number. This is happening because you have set input type to number. You can try this Please check this thread https://stackoverflow.com/a/31706796/5238397

1

Remove other chars when inputted:

const input = document.querySelector('input');
input.oninput = (e) => {e.target.value = e.target.value.replace(/[^0-9]/g,"");}
<input type="number">
Ritesh Khandekar
  • 3,885
  • 3
  • 15
  • 30
  • Thank you for the suggestion, Ritesh I also tried this approach initially and ended up with previous value being replaced with an empty string which isn't the desired output for the case I am working with. But thank you anyway for your help :-) – volna Jan 25 '20 at 05:40