如何允许用户覆盖输入类型数字中的数字(如果已经有两个数字)? [英] How can I allow users to overwrite the numbers in the input type number (when there are already two numbers)?

查看:39
本文介绍了如何允许用户覆盖输入类型数字中的数字(如果已经有两个数字)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请参见下面的JavaScript:

Please see the JavaScript below:

maxLengthDay(event) {
    const maxLength = 2;
    if (event.target.value.length + 1 > maxLength)
      return false;
    else
      return true;
  }

和以下HTML:

<input (keypress)="maxLengthDay($event)" type="number" />

它可以按预期工作,即确保输入框最多仅包含两个字符.如果用户突出显示该数字(特别是在有两个数字时)并尝试覆盖一个或两个数字,则会出现问题.什么也没发生,因为输入控件此时包含两个数字.

It works as expected i.e. it ensures the input box only contains two characters at most. The problem occurs if the user highlights the number (specifically when there are two numbers) and try to overwrite one or two numbers. Nothing happens because the input control contains two numbers at that point.

如何允许用户覆盖输入控件中的数字(如果已经有两个数字)?

How can I allow users to overwrite the numbers in the input control (when there are already two numbers)?

推荐答案

也许,您可以添加一个带有超时的处理程序,该处理程序将允许用户继续输入值,但仅保留最后输入的2位数字.

Perhaps, you could add a handler with timeout that will allow user to continue entering values, but retain only last entered 2 digits.

为使代码段正常工作,以下示例基于纯JS.它也可以扩展为在Angular代码中使用.

For snippet to work, below example is pure JS based. It can be extended to be used in Angular code as well.

function maxLengthDay(event) {
  setTimeout(() => {
    const maxLength = 2;
    if (event.target.value.length + 1 > maxLength) {
      var v = event.target.value;
      event.target.value = event.target.value.substr(v.length - 2, v.length);
    }
  }, 0);
}

document.addEventListener('keypress', maxLengthDay);
document.addEventListener('paste', maxLengthDay);

<input  type="number" />

这篇关于如何允许用户覆盖输入类型数字中的数字(如果已经有两个数字)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆