i need to set an input field that should accept only numbers 1,2,3,4,5,6,7,8,9,10, it should only accept single digits
<input
type="number"
step="1" // Set step to "1" to allow only single-digit numbers
min="1"
max="10"
value={skill.editedRating || skill.rating}
onChange={(e) => handleRatingChange(e, skill.skillId)}
onKeyDown={(e) => handleKeyDown(e)}
/>
const handleKeyDown = (event) => {
const input = event.target;
const inputValue = input.value;
// Check if the input value contains more than one digit
if (inputValue.length > 1) {
// Clear the input field and set it to the last digit entered
input.value = inputValue.charAt(inputValue.length - 1);
}
};
const handleRatingChange = (event, Id) => {
const arr = skills.filter((element) => {
if (element.skillId == Id) {
element.rating = event.target.value;
}
return element;
});
setSkills(arr);
};
this is my code now its accepting 2 digits instead of one.
2
Answers
You could check your min and max value. Whenever it exceeds one of these, replace the value with the correct value:
You might need to change the input event
onKeyDown
toonInput
, just because without this, the event doesn’t pick up the current changes made.You might also need to modify your
handleKeyDown
function slightly thus: