skip to Main Content

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


  1. You could check your min and max value. Whenever it exceeds one of these, replace the value with the correct value:

    function restrictInputRange(input) {
        const min = parseFloat(input.min);
        const max = parseFloat(input.max);
        const value = parseFloat(input.value);
    
        // Not a number? Empty input
        if (isNaN(value)) {
          input.value = ''
          return
        }
        
        // Now we know it's a number,
        // Check if it exceeds a limit
        if (value < min) {
            input.value = min;
        } else if (value > max) {
            input.value = max;
        }
    }
    <label for="numberInput">Enter a number between 1 and 10:</label>
    <input type="number" id="numberInput" min="1" max="10" oninput="restrictInputRange(this)">
    Login or Signup to reply.
  2. You might need to change the input event onKeyDown to onInput, 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:

      // It's worth renaming this function to handleInput
      const handleKeyDown = (event) => {
        const input = event.target;
        let inputValue = input.value;
    
        // Check if the input value is greater than 10 or starts with a zero
        if (inputValue > 10 || inputValue.toString().startsWith("0")) {
          // Clear the input field and set it to the last digit entered
          input.value = inputValue.charAt(inputValue.length - 1);
        }
      };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search