0

I am trying to remove invalid characters and convert them to uppercase;

If you run the code on latest Firefox for Android, the input event will be fired twice and the input value will be duplicated.

But if you remove any manipulations (toUpperCase or replace), then the problem disappears.

Test case one (with the problem)

var input = document.getElementById("a");
input.addEventListener("input", ()=>{
    //input.value = input.value.toUpperCase();
  //input.value = input.value.replace(/[^A-Z]/gi);
  input.value = input.value.toUpperCase().replace(/[^A-Z]/gi, '');

  console.log("event");
});
<input id="a" type="text">

Test case two (without the problem)

var input = document.getElementById("a");
input.addEventListener("input", ()=>{
    //input.value = input.value.toUpperCase();
  input.value = input.value.replace(/[^A-Z]/gi, '');
  //input.value = input.value.toUpperCase().replace(/[^A-Z]/gi, '');

  console.log("event");
});
<input id="a" type="text">

What is the reason of the behavior and how to fix it?

EDIT:: Screenshot for clarity. I entered "ABC" Screenshot

EDIT 2: It looks like this code is causing a problem on apple mobile devices - when clicking on keyboard hints, these hints are not used. A temporary solution is to use filtering (replace) at the input event, and use uppercase - through the focusout or via css (text-transform: uppercase) and further transformation on the server

Andrew G
  • 97
  • 1
  • 7
  • @Liam I don't why, but some Firefox for Android show the error and some work correctly. – Andrew G Oct 13 '20 at 13:39
  • Don't you think that Firefox for Android is right and other browser aren't. After all when you do `input.value = input.value.toUpperCase().replace(/[^A-Z]/gi, '');` it is normal that the `input` event would be trigger. If this is the origine of your problem, maybe you could use the `isTrusted` property of the event. – Cedric Cholley Oct 13 '20 at 14:09
  • @CedricCholley Your argument looks logical, but why then doesn't it work exactly the same when `input.value = input.value.replace(/[^A-Z]/gi);`? – Andrew G Oct 13 '20 at 14:14
  • Good point. I don't believe it is related but isn't the second argument missing in `.replace(…)` – Cedric Cholley Oct 13 '20 at 14:17
  • This is a missprint. Instead `.replace(...)` the same result with `toUpperCase()` – Andrew G Oct 13 '20 at 14:19
  • My first idea is probably not a good direction – Cedric Cholley Oct 13 '20 at 14:22

0 Answers0