[英]Prevent users from entering a value greater than 2 digits in an input field
I have a HTML form field to get the month from the user. 我有一个HTML表单字段,可以从用户那里获取月份。
<input type="text" placeholder="MM" size="2" name="month">
I need the field to accept only 2 digits. 我需要该字段仅接受2位数字。 I tried Form validation, but it allows the user to enter more than 2 digits and then display the validation message. 我尝试了表单验证,但是它允许用户输入2位以上的数字,然后显示验证消息。 I don't need any validation messages for the field, but the user should be restricted to enter only 2 digits max. 我不需要该字段的任何验证消息,但是应该限制用户最多只能输入2位数字。 Is there a way we can do this using jquery? 有没有一种方法可以使用jquery做到这一点?
<input type="text" placeholder="MM" size="2" name="month" maxlength="2>
The maxlength
attribute; maxlength
属性;
<input type="text" placeholder="MM" size="2" maxlength="2" name="month">
It limits the amount of text you can enter by straight up not allowing you to type more. 它限制了您可以直接输入的文本数量,不允许您键入更多内容。
EDIT: added snippet 编辑:添加了代码段
The easiest is using the type='number'
attribute and setting max='12'
: 最简单的方法是使用type='number'
属性并设置max='12'
:
<input type='number' max='12' min='1'>
input { width: 4ex; padding: 0 1px; } input:last-of-type { width: 6.5ex; }
<fieldset> <legend>Enter Date</legend> <label>Month:</label> <input type='number' max='12' min='1'> <label>Day:</label> <input type='number' max='31' min='1'> <label>Year:</label> <input type='number' max='3000' min='2016'> </fieldset>
This should help you out, whenever the user presses the key down it will check the lenght and then trim the extra chars if there are any: 这应该可以为您提供帮助,每当用户按下按键时,它就会检查长度,然后修剪多余的字符(如果有):
$("input").keydown(function() {
var value = $(this).val();
if(value.length > 2) {
value = value.substring(0, 2);
$(this).val(value);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.