HTML 数字输入最小值和最大值无法正常工作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32936352/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 18:19:09  来源:igfitidea点击:

HTML number input min and max not working properly

html

提问by Tomas Dohnal

I have type=numberinput field and I have set minand maxvalues for it:

我有type=number输入字段,我有设置minmax值是:

<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.

当我使用输入字段右侧的小箭头更改渲染 UI 中的时间时,一切正常 - 我不能超过 23 或低于 0。但是,当我手动输入数字时(使用键盘),那么这两个限制都不起作用。

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

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

采纳答案by Praveen Kumar Purushothaman

With HTML5 maxand 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:

使用 HTML5maxmin,您只能将值限制为输入数字。但是您需要使用 JavaScript 或 jQuery 来进行这种更改。我的一个想法是使用data-属性并保存旧值:

$(function () {
  $("input").keydown(function () {
    // Save old value.
    if (!$(this).val() || (parseInt($(this).val()) <= 11 && parseInt($(this).val()) >= 0))
    $(this).data("old", $(this).val());
  });
  $("input").keyup(function () {
    // Check correct, else revert back to old value.
    if (!$(this).val() || (parseInt($(this).val()) <= 11 && 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" />

回答by George Wilson

Maybe Instead of using the "number" type you could use the "range" type which would restrict the user from entering in numbers because it uses a slide bar and if you wanted to configure it to show the current number just use JavaScript

也许不是使用“数字”类型,您可以使用“范围”类型,它会限制用户输入数字,因为它使用滑动条,如果您想将其配置为显示当前数字,只需使用 JavaScript

回答by user2061057

In some cases patterncan be used instead of minand max. It works correctly with required.

在某些情况下pattern可以代替minand 使用max。它与required.

回答by Antony

$(document).ready(function(){
    $('input[type="number"]').on('keyup',function(){
        v = parseInt($(this).val());
        min = parseInt($(this).attr('min'));
        max = parseInt($(this).attr('max'));

        /*if (v < min){
            $(this).val(min);
        } else */if (v > max){
            $(this).val(max);
        }
    })
})

Here is my contribution. Note that the v < min is commented out because I'm using Bootstrap which kindly points out to the user that the range is outside the 1-100 but wierdly doesn't highlight > max!

这是我的贡献。请注意, v < min 被注释掉了,因为我使用的是 Bootstrap,它善意地向用户指出范围在 1-100 之外,但奇怪的是没有突出显示 > max!

回答by Vincent

Despite the HTML5 enforcement of min and max on the up/down arrows of type=number control, to really make those values useful you still have to use Javascript.

尽管 HTML5 在 type=number 控件的向上/向下箭头上强制执行 min 和 max ,但要真正使这些值有用,您仍然必须使用 Javascript

Just save this function somewhere and call it on keyup for the input.

只需将此函数保存在某处并在 keyup 上调用它以进行输入。

function enforceMinMax(el){
  if(el.value != ""){
    if(parseInt(el.value) < parseInt(el.min)){
      el.value = el.min;
    }
    if(parseInt(el.value) > parseInt(el.max)){
      el.value = el.max;
    }
  }
}

Like so...

像这样...

<input type="number" min="0" max="23" value="14" onkeyup=enforceMinMax(this)>

回答by Pars

One event listener, No data-attribute.

event listener,无data-属性。

You can simply prevent it by using following script:

您可以使用以下脚本简单地阻止它:

$(document).on('keyup', 'input[name=quantity]', function() {
  var _this = $(this);
  var min = parseInt(_this.attr('min')) || 1; // if min attribute is not defined, 1 is default
  var max = parseInt(_this.attr('max')) || 100; // if max attribute is not defined, 100 is default
  var val = parseInt(_this.val()) || (min - 1); // if input char is not a number the value will be (min - 1) so first condition will be true
  if (val < min)
    _this.val(min);
  if (val > max)
    _this.val(max);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" class="form-control" name="quantity" max="250" min="1" value="">

The only problem is: You can't type -to get negative numbers if your minis lower than 0

唯一的问题是-如果min小于 0,则无法输入以获取负数

回答by Meri? Güng?r

$(document).on('keyup', 'input[type=number][min],input[type=number][max]', function () {
    var _this = $(this);
    if (_this.val() === "-")
        return;

    var val = parseFloat(_this.val());

    if (_this.attr("min") !== undefined && _this.attr("min") !== "") {
        var min = parseFloat(_this.attr('min'));

        if (val < min)
            _this.val(min);
    }
    if (_this.attr("max") !== undefined && _this.attr("max") !== "") {
        var max = parseFloat(_this.attr('max'));

        if (val > max)
            _this.val(max);
    }
});
$(document).on('change', 'input[type=number][step]', function () {
    var _this = $(this);

    var val = parseFloat(_this.val());

    if (_this.attr("step") !== undefined && _this.attr("step") !== "") {
        var step = parseFloat(_this.attr('step'));

        if ((val % step) != 0)
            _this.val(val - (val % step));
    }
});

回答by CreativeMinds

Use this range method instead of number method.

使用此范围方法而不是数字方法。

$(function () {
  $("#input").change(function () {
    // Save old value.
    $("#limit").val($("#input").val());
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="limit" name="limit" value="14" readonly><br>
<input type="range" id="input" name="input" min="0" max="23" value="14"/>

回答by horiatu

Forget the keydown or keyup: it won't let you enter like 15 or 20 if the min was set to 10! Use the change event since this is where the input value goes in your business logic (ViewModel):

忘记 keydown 或 keyup:如果 min 设置为 10,它不会让您输入 15 或 20!使用 change 事件,因为这是输入值在您的业务逻辑 (ViewModel) 中的位置:

private _enforceMinMax = (input:HTMLInputElement) => {
    console.log("input", input);
    const v = parseFloat(input.value);
    if(input.hasAttribute("min")) {
        const min = parseFloat(input.min);
        if(v < min) {
            input.value = min+"";
        }
    }
    if(input.hasAttribute("max")) {
        const max = parseFloat(input.max);
        if(v > max) {
            input.value = max+"";
        }
    }
}

private _distanceChange = (event) => {
    this._enforceMinMax(event.target);
    ...

回答by Gon?alo

$(function () {
  $("input").keydown(function () {
    // Save old value.
    if (!$(this).val() || (parseInt($(this).val()) <= 11 && parseInt($(this).val()) >= 0))
    $(this).data("old", $(this).val());
  });
  $("input").keyup(function () {
    // Check correct, else revert back to old value.
    if (!$(this).val() || (parseInt($(this).val()) <= 11 && 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" />