While bored and scrolling through videos, I came across a video:
So I decided to try it myself and indeed found this issue to be true. I also tested some of the fixes suggested by Xiaoshan and they did fix the problem. However, during my testing, I accidentally discovered that when typing in Chinese, pressing the ⬆️ or ⬇️ keys on the keyboard would modify the value of the input:number
text box. I realized that this behavior is not what users would expect, and the value should not change in this case. So I attempted to fix this issue. Below is an example of my fix code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Buyu</title>
</head>
<body>
<input style="text-align: center;" type="number">
<script>
const input = document.querySelector("input");
const numberReg = /^\d+$/g;
let lock = false;
input.addEventListener("input", (e) => {
if (e.target.type !== "number") return;
if (e.data && !numberReg.test(e.data)) lock = true;
else if (!e.data) lock = false;
if (e.target.value === "" && e.data === "") {
e.target.value = 0;
setTimeout(() => e.target.value = "");
}
});
function stopInputNumberEvent(event) {
if (lock && (event.key === "ArrowDown" || event.key === "ArrowUp") && event.target.type === 'number') {
event.preventDefault();
}
};
input.addEventListener("focus", (e) => {
document.addEventListener("keydown", stopInputNumberEvent);
});
input.addEventListener("blur", (e) => {
document.removeEventListener("keydown", stopInputNumberEvent);
});
</script>
</body>
</html>
The main methods used to fix this issue are:
- Listening for keyboard events and blocking the default behavior at the appropriate time.
- Checking if the user input is a non-numeric value.
- Note that
event.data
ande.target.value
in theinput
event are different. One represents the current input value, while the other represents the value in the input box.
- Note that
This issue exists in native browsers and is not related to any framework or other factors.
During my testing, I used Chrome version 115.0.5790.114 on MacOS 13.5 (22G74).