简体   繁体   中英

Prevent maxLength on number input from constantly changing value on last number?

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.

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)" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM