限制用户将值放在html输入中的范围内(类型=数字) [英] Restrict user to put value in range in html input (type = number)

查看:303
本文介绍了限制用户将值放在html输入中的范围内(类型=数字)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何阻止用户在html输入(类型=数字)中添加大于最大值且小于最小值的数字

How can I stop user from adding number greater than max value and smaller then min value in html input(type = number)

<input id="ageRange" type="number" min=20 max= 50 maxlength=2></input>

我尝试了一个javascript代码,但是在添加值之后进行了更改,然后更改了值.有什么方法可以阻止用户将值放在范围内,或者在以编程方式更改值时输入单元格中没有闪烁?

I tried one javascript code, but it makes change after we add the value then it changes the value. Is there any way that I can stop user to put value in range or just there is no flickering in the input cell while we change value programatically?

推荐答案

您将需要在较低级别处理输入并执行自己的检查.为了防止用户键入的值大于最大值,可以处理keypress事件,然后检查输入字符以及它是否会使值过大:

You would need handle input at a low level and perform your own checks. To prevent the user from typing value larger than the maximum, you could handle the keypress event and then check the input character and whether it would make the value too large:

<input id="ageRange" type="number" min=20 max= 50 maxlength=2>
<script>
document.getElementById('ageRange').onkeypress =
  function (e) {
    var ev = e || window.event;
    if(ev.charCode < 48 || ev.charCode > 57) {
      return false; // not a digit
    } else if(this.value * 10 + ev.charCode - 48 > this.max) {
       return false;
    } else {
       return true;
    }
  }
</script>

这确实防止用户通过粘贴插入较大的值.

This does prevent the user from inserting a larger value by pasting.

为防止用户删除字符以使该值变得太小,您将需要处理外键,由于键盘的不同,这会带来更多问题.但这会降低可用性.假设用户键入30,然后意识到他要键入40.防止将值更改为太小的代码将阻止删除任何一个数字!

To prevent the user from deleting characters so that the value becomes too small, you would need to handle the rubout key, which is more problematic due to keyboard differences. But it would be poor usability. Suppose the user typed 30, then realized he meant to type 40. A code that prevents changing the value to too small would prevent removing either digit!

浏览器应该具有自己的<input type=number>用户界面,这就是使用它的原因.该界面并不是要防止用户键入太大的值,而是要检测它们并报告它们,以便用户可以对其进行更正.在尝试对此进行实质性修改之前,请考虑潜在的混淆.如果您确实添加了防止超出范围的值的代码,则浏览器将不会显示诊断消息(例如,数字必须小于或等于50"),因为它们默认支持<input type=number>,因此它们会默认显示代码可能应该发出自己的诊断信息.

Browsers are expected to have their own user interface for <input type=number>, and this is the reason for using it. The interface is not meant to prevent the user from typing too large values but to detect them and report them so that the user can correct them. Before trying to substantially modify this, consider the potential confusion. If you do add code that prevents out-of-ranfe values, browsers will not show diagnostic messages (e.g. "Number must be less than or equal to 50"), as they do by default if they support <input type=number>, so your JavaScript code should probably issue its own diagnostics.

这篇关于限制用户将值放在html输入中的范围内(类型=数字)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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