I have the below code to allow the user input only numbers, this works in browser. But when I access on mobile I think I am not able to get the right key code. So what are the keycodes for the same. Isn't same as the web.
// block e char, dot, hiphen and spacebar
if (event.key === 'e' || [46, 45, 32].includes(event.charCode)) {
event.preventDefault();
}else{
// allow to input logic
}
What are the charCode for dot, hyphen and space which will work for both web and mobile keypad ?
Your code is using event.charCode, which does not exist.
event.which.charCode does. Also you do not tell us what event. There are keypress, keydown, keyup, input and some do not set some of the expected event values
Tested on Android and iOS using browserstack
Only one that seems to work in React on Android
export default function App() {
const handleInput = (event) => {
// eslint-disable-next-line
event.target.value = event.target.value.replace(/[e\.\- ]/g, "");
console.log(event.target.value);
};
return (
<div className="App">
<input type="number" onInput={handleInput} />
</div>
);
}
Keydown and the code names which is recommended
document.getElementById("positiveIntOnly").addEventListener("keydown",function(e) {
// block e char, dot, hyphen and spacebar
if (["KeyE", "Period", "Minus", "Space"].includes(e.code)) {
event.preventDefault();
console.log(e.code);
}
});
<input type="number" id="positiveIntOnly" />
Or as mentioned by TJ, e.key:
document.getElementById("positiveIntOnly").addEventListener("keydown",function(e) {
// block e char, dot, hyphen and spacebar
if ("e.- ".includes(e.key)) {
event.preventDefault();
console.log(e.key);
}
});
<input type="number" id="positiveIntOnly" />
Set a min and max and use a regexp to handle paste
<input type="number" id="positiveIntOnly" min="0" max="999" step="1"
oninput="this.value = this.value.replace(/[e\.\- ]/g,'')" />
You can just you the key property:
["e" ,"E", "-", ".", " "].includes(e.key)
You're not supposed to use the charCode property as it is deprecated.