简体   繁体   English

防止用户在输入字段中输入大于2位数字的值

[英]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'>

SNIPPET SNIPPET

 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.

相关问题 如何防止用户在输入字段中输入无效字符 - How to prevent users from entering invalid characters inside an input field 阻止用户使用HTML5在输入文本字段中输入非数字 - Preventing users from entering non-digits in input text field with HTML5 阻止用户输入一个浮点数,该数字大于3位小数 - Prevent user from entering a float number, greater than 3 decimals 验证输入字段的值大于另一个 - Verifying that the value of a input field is greater than another 防止用户在输入框中手动输入日期 - Prevent users from manually entering dates in input boxen 如何使用正则表达式验证防止用户在输入中输入逗号? - How to prevent users from entering a comma in an input with regex validation? 输入字段值不应大于其他字段值 - Input field value should not be greater than other field value 如果一定数量的数字已经具有值,则阻止用户在输入字段中输入数字 - Prevent the user from entering a number in the input field if a certain number of them already have a value 如何防止可选输入字段的占位符值在离开数据库时进入数据库? - How to prevent an optional input field's placeholder value from entering into the database on leaving it? 如何防止用户选择大于今天的日期? - How to prevent users from choosing a date greater than today?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM