HTML数字输入最小和最大不能正常工作 [英] HTML number input min and max not working properly

查看:126
本文介绍了HTML数字输入最小和最大不能正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 type = number 输入字段,并且设置了 min max 值:

 < input type =numbermin =0max = 23值=14> 

当我在渲染UI中使用右侧的小箭头更改时间时输入字段,一切工作正常 - 我不能超过23或0以下。但是,当我手动输入数字(使用键盘),然后没有任何限制有效。



有没有办法阻止任何人输入他们想要的数字?

使用HTML5 max min ,您只能限制数值输入数字。但是你需要使用JavaScript或者jQuery来做这种改变。我有一个想法是使用 data - 属性并保存旧值:

$ (function(){$(input)。keydown(function(){//保存旧值$(this).data(old,$(this).val());}); $(如果(parseInt($(this).val())< = 23&&& parseInt($(this)),则返回原始值。 .val())> = 0); else $(this).val($(this).data(old));});}); < script src =https://ajax.googleapis.com/ajax/libs/jquery/1.9。

pre>


I have type=number input field and I have set min and max values for it:

<input type="number" min="0" max="23" value="14">

When I change the time in the rendered UI using the little arrows on the right-hand side of the input field, everything works properly - I cannot go either above 23 or below 0. However, when I enter the numbers manually (using the keyboard), then neither of the restrictions has effect.

Is there a way to prevent anybody from entering whatever number they want?

解决方案

With HTML5 max and min, you can only restrict the values to enter numerals. But you need to use JavaScript or jQuery to do this kind of change. One idea I have is using data- attributes and save the old value:

$(function () {
  $("input").keydown(function () {
    // Save old value.
    $(this).data("old", $(this).val());
  });
  $("input").keyup(function () {
    // Check correct, else revert back to old value.
    if (parseInt($(this).val()) <= 23 && parseInt($(this).val()) >= 0)
      ;
    else
      $(this).val($(this).data("old"));
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="number" min="0" max="23" value="14" />

这篇关于HTML数字输入最小和最大不能正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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