如何通过javascript或jquery设置html5中的最大值和最小值

时间:2022-09-26 21:26:58

I am trying to find out how to set the max value and min value of html5 type input by javascript or jquery.

我试图找出如何通过javascript或jquery设置html5类型输入的最大值和最小值。

<input type="number" max="???" min="???" step="0.5"/>

Would someone please guide

有人请指导

3 个解决方案

#1


31  

jQuery makes it easy to set any attributes for an element - just use the .attr() method:

jQuery可以轻松设置元素的任何属性 - 只需使用.attr()方法:

$(document).ready(function() {
    $("input").attr({
       "max" : 10,        // substitute your own
       "min" : 2          // values (or variables) here
    });
});

The document ready handler is not required if your script block appears after the element(s) you want to manipulate.

如果脚本块出现在要操作的元素之后,则不需要文档就绪处理程序。

Using a selector of "input" will set the attributes for all inputs though, so really you should have some way to identify the input in question. If you gave it an id you could say:

使用“input”的选择器将设置所有输入的属性,所以实际上你应该有一些方法来识别有问题的输入。如果你给它一个id,你可以说:

$("#idHere").attr(...

...or with a class:

......或与班级:

$(".classHere").attr(...

#2


12  

Try this:

尝试这个:

<input type="number" max="???" min="???" step="0.5" id="myInput"/>

$("#myInput").attr({
   "max" : 10,
   "min" : 2
});

Note:This will set max and min value only to single input

注意:这将仅将最大值和最小值设置为单个输入

#3


6  

Try this

尝试这个

 $(function(){
   $("input[type='number']").prop('min',1);
   $("input[type='number']").prop('max',10);
});

Demo

演示

#1


31  

jQuery makes it easy to set any attributes for an element - just use the .attr() method:

jQuery可以轻松设置元素的任何属性 - 只需使用.attr()方法:

$(document).ready(function() {
    $("input").attr({
       "max" : 10,        // substitute your own
       "min" : 2          // values (or variables) here
    });
});

The document ready handler is not required if your script block appears after the element(s) you want to manipulate.

如果脚本块出现在要操作的元素之后,则不需要文档就绪处理程序。

Using a selector of "input" will set the attributes for all inputs though, so really you should have some way to identify the input in question. If you gave it an id you could say:

使用“input”的选择器将设置所有输入的属性,所以实际上你应该有一些方法来识别有问题的输入。如果你给它一个id,你可以说:

$("#idHere").attr(...

...or with a class:

......或与班级:

$(".classHere").attr(...

#2


12  

Try this:

尝试这个:

<input type="number" max="???" min="???" step="0.5" id="myInput"/>

$("#myInput").attr({
   "max" : 10,
   "min" : 2
});

Note:This will set max and min value only to single input

注意:这将仅将最大值和最小值设置为单个输入

#3


6  

Try this

尝试这个

 $(function(){
   $("input[type='number']").prop('min',1);
   $("input[type='number']").prop('max',10);
});

Demo

演示