Reputation: 5508
I have an input field within ReactJS like so:
<input
type="number"
onKeyPress={handleKeyPress}
maxLength={3}
min="0"
max="999"
step=".1"
onPaste={handlePaste}
/>
Here are the associated functions for that input:
function handleKeyPress(e) {
if (e.target.value.length > e.target.maxLength) {
e.target.value = e.target.value.slice(0, e.target.maxLength);
}
const key = e.key;
if (!allowChars(key)) {
e.preventDefault();
}
}
function allowChars(charValue) {
const acceptedKeys = '0123456789';
return acceptedKeys.indexOf(charValue) > -1;
}
function handlePaste(event) {
event.preventDefault();
}
Now every time I reach 3 characters, a 4th character is able to be typed constantly. Please see the attached GIF for an example:
Any ideas on how I can prevent this? I just want the input field to have a max of 3 characters, so the 4th character should not even show up.
Upvotes: 2
Views: 1231
Reputation: 42054
Your issue is in this code fragment:
if (e.target.value.length > e.target.maxLength) {
e.target.value = e.target.value.slice(0, e.target.maxLength);
}
Change it to:
if (e.target.value.length >= e.target.maxLength) {
e.target.value = e.target.value.slice(0, e.target.maxLength);
e.preventDefault();
return;
}
function handleKeyPress(e) {
if (e.target.value.length >= e.target.maxLength) {
e.target.value = e.target.value.slice(0, e.target.maxLength);
e.preventDefault();
return;
}
const key = e.key;
if (!allowChars(key)) {
e.preventDefault();
}
}
function allowChars(charValue) {
const acceptedKeys = '0123456789';
return acceptedKeys.indexOf(charValue) > -1;
}
function handlePaste(event) {
event.preventDefault();
}
<input
type="number"
onKeyPress="handleKeyPress(event)"
maxLength="3"
min="0"
max="999"
step=".1"
onPaste="handlePaste(event)"
/>
Upvotes: 2