Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
219 views
in Technique[技术] by (71.8m points)

javascript - 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?

question from:https://stackoverflow.com/questions/65881648/setting-input-value-when-keydown-event-triggered-is-incorrect-on-ipados-14-safar

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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"/>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...