Search code examples
javascriptsafaricjkipados

Setting input value when keydown event triggered is incorrect on iPadOS 14 Safari


Use following code in html:

<input id="test" autocomplete="off" inputmode="numeric"/>
<script>
var input = document.getElementById('test');
input.addEventListener('keydown', function(e){
     input.value = 34;
})
</script>

Enviroment
iPadOS14 + Safari + Japanese keyboard

Steps:
1. focus on the input to open the keyboard.
2. switch to Japanese keyboard
3. press any number button like 2, 3, etc.
4. it's observered that input value is 342 or 343 instead of 34.

Expected: input value should be 34.

Known workaround:
using setTimeout to update the iput value when key down.

setTimeout(() => {
    input.value = 34;
}, 20)

My question is that is there any better solution to solve this issue?


Solution

  • The described problem is not related specifically to the Japanese key board - you can demonstrate the same thing with the English keyboard.

    It's related to the order of events. On keydown, you see the event but at that time the input.value has not been updated by the system. So when you write 34 into the value, subsequently the system sees a keyup and at that point writes the key into the value - concatenated to any value that is already there.

    So, if you listen for keyup you will get the result you want, the system will have put the pressed key code into input.value, you will then overwrite it with 34.

    var input = document.getElementById('test');input.addEventListener('keyup', function(e){
         input.value = 34;
    })
    <input id="test" autocomplete="off" inputmode="numeric"/>