[英]Error message when a user enters more characters than max length on text area
How can I return an error message to users when they try to go past the max length in a text area?当用户尝试超过文本区域中的最大长度时,如何向用户返回错误消息?
Is there a way for HTML to return an error to the user? HTML有没有办法向用户返回错误?
<input type="text" name="fieldname" maxlength="10">
You can use the maxlenght
attribute to forbid entering more characters than intended.您可以使用maxlenght
属性来禁止输入比预期更多的字符。 You will not need JS for this.为此,您将不需要 JS。
If you still want to use JS, then:如果你还想用JS,那么:
$("#myformid").keypress(function() {
if($(this).val().length > 10) {
//display your warinig the way you chose
}
]
});
Sure this is possible!当然这是可能的! First, count the entered characters and then print out the message you'd like to (here: "Characters left: X", the max length is 100 in my example).首先,计算输入的字符数,然后打印出您想要的消息(此处:“剩余字符数:X”,在我的示例中最大长度为 100)。
Here is the JSFiddle !这是JSFiddle !
HTML: HTML:
<textarea rows="4" cols="50" id ="yourtextarea">
</textarea>
<div id="info"></div>
JS: JS:
$("#yourtextarea").keyup(function(){
$("#info").text("Characters left: " + (100 - $(this).val().length));
});
function check_length(my_form)
{
maxLen = 50; // max number of characters allowed
if (my_form.my_text.value.length >= maxLen) {
var msg = "You have reached your maximum limit of characters allowed";
alert(msg);
my_form.my_text.value = my_form.my_text.value.substring(0, maxLen);
}
}
<textarea onKeyPress=check_length(this.form); onKeyDown=check_length(this.form); name=my_text rows=4 cols=30></textarea>
Here's the code to validate user input without having to use Jquery.这是无需使用 Jquery 即可验证用户输入的代码。
<textarea id=txt onKeyUp=check() maxlength=10>
Abc
</textarea>
<div id=warning></div>
<script>
function check() {
stringLength = document.getElementById('txt').value.length;
if (stringLength >= 10) {
document.getElementById('warning').innerText = "Maximum characters are 10"
} else {
document.getElementById('warning').innerText = ""
}
}
</script>
A solution for all input fields that has MAXLENGTH attribute defined, so that you don't have to apply size for each element.适用于定义了MAXLENGTH 属性的所有输入字段的解决方案,因此您不必为每个元素应用大小。
$("input[maxlength], textarea[maxlength]").keyup(function () {
var max = $(this).prop('maxlength');
if ($(this).val().length > max) {
alert('value must be less than ' + max + ' characters');
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.