jQuery 如何防止用户在达到最大字符限制后在 textarea 中输入文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10414420/
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
How to prevent user to enter text in textarea after reaching max character limit
提问by Basit
I want to prevent user to enter text in textarea once it reaches a max character limit. What was happening that when i reached to max limit then my text-area scroll-bar moved to top I somehow prevent this with this code.
一旦达到最大字符限制,我想阻止用户在 textarea 中输入文本。发生了什么,当我达到最大限制然后我的文本区域滚动条移到顶部时,我以某种方式使用此代码阻止了这种情况。
jQuery(document).ready(function($) {
$('textarea.max').keyup(function() {
var $textarea = $(this);
var max = 400;
if ($textarea.val().length > max) {
var top = $textarea.scrollTop();
$textarea.val($textarea.val().substr(0, max));
$textarea.scrollTop(top);
}
});
}); //end if ready(fn)
But i also want that after reaching max limit user unable to type anything in the textarea. Currently what happen that after reaching max limit if user press and hold the key, the characters are typing in the text area, although after releasing the button it come back to original text (i.e $textarea.val($textarea.val().substr(0, max)); ). But i want that once this condition become true
但我也希望在达到最大限制后用户无法在 textarea 中输入任何内容。目前,如果用户按住该键,达到最大限制后,字符会在文本区域中输入,但释放按钮后会返回原始文本(即 $textarea.val($textarea.val())。 substr(0, max)); )。但我希望一旦这种情况成为现实
if ($textarea.val().length > max) {
user unable to type anything. I want that cursor vanishes from the textarea. But if user remove some text then cursor also available for user to type input again. How can I do it?
用户无法输入任何内容。我希望光标从 textarea 中消失。但是如果用户删除一些文本,则光标也可供用户再次输入。我该怎么做?
回答by Rob W
The keyup
event fires after the default behaviour (populating text area) has occurred.
该keyup
事件在默认行为(填充文本区域)发生后触发。
It's better to use the keypress
event, and filter non-printable characters.
最好使用keypress
事件,并过滤不可打印的字符。
Demo: http://jsfiddle.net/3uhNP/1/(with max length 4)
演示:http: //jsfiddle.net/3uhNP/1/(最大长度为 4)
jQuery(document).ready(function($) {
var max = 400;
$('textarea.max').keypress(function(e) {
if (e.which < 0x20) {
// e.which < 0x20, then it's not a printable character
// e.which === 0 - Not a character
return; // Do nothing
}
if (this.value.length == max) {
e.preventDefault();
} else if (this.value.length > max) {
// Maximum exceeded
this.value = this.value.substring(0, max);
}
});
}); //end if ready(fn)
回答by KBN
<textarea maxlength="400"> </textarea>
Use the above code to limit the number of characters inserted in a text area, if you want to disable the textarea itself (ie, will not be able to edit afterwards) you can use javascript/jquery to disable it.
使用上面的代码来限制文本区域插入的字符数,如果你想禁用文本区域本身(即之后将无法编辑)你可以使用javascript/jquery来禁用它。
回答by Joseph Fizzy Beats
Keep it simple
把事情简单化
var max = 50;
$("#textarea").keyup(function(e){
$("#count").text("Characters left: " + (max - $(this).val().length));
});
and add this in your html
并将其添加到您的 html 中
<textarea id="textarea" maxlength="50"></textarea>
<div id="count"></div>
回答by GuRu
You could directly give maxlength
to textarea
to disable itself. But, you want to showing appropriate message then use keyup
event for default behavior and textarea
length
for calculating charcter and display suitable message.
你可以直接给maxlength
到textarea
禁用本身。但是,您希望显示适当的消息,然后将keyup
事件用于默认行为和textarea
length
计算字符并显示合适的消息。
HTML
HTML
<div id="count"></div>
<textarea class="max" maxlength="250" id="tarea"></textarea>
<div id="msg"></div>
jQuery
jQuery
$(function(){
var max = parseInt($("#tarea").attr("maxlength"));
$("#count").text("Characters left: " + max);
$("#tarea").keyup(function(e){
$("#count").text("Characters left: " + (max - $(this).val().length));
if($(this).val().length==max)
$("#msg").text("Limit Reached....");
else
$("#msg").text("");
});
});
回答by ViPuL5
Just write this code in your Javascript file.. But Need to specify the 'maxlength' attribute with textarea. This will work for all textarea of a page.
只需在您的 Javascript 文件中编写此代码。但需要使用 textarea 指定“maxlength”属性。这将适用于页面的所有文本区域。
$('textarea').bind("change keyup input",function() {
var limitNum=$(this).attr("maxlength");
if ($(this).val().length > limitNum) {
$(this).val($(this).val().substring(0, limitNum));
}
});
回答by arb
回答by Gus
For those already using ES2015 in your browsers, here's an implementation using some of the answers above:
对于那些已经在浏览器中使用 ES2015 的人,这里有一个使用上面的一些答案的实现:
class InputCharacterCount {
constructor(element, min, max) {
this.element = element;
this.min = min;
this.max = max;
this.appendCharacterCount();
}
appendCharacterCount(){
let charCount = `<small class="char-counter help-block"></small>`;
this.element.closest('.form-group').append(charCount);
}
count(event){
this.element.attr('maxlength', this.max); // Add maxlenght attr to input element
let value = this.element.val();
this.element
.closest('.form-group')
.find('.char-counter')
.html(value.length+'/'+this.max); // Add a character count on keyup/keypress
if (value.length < this.min || value.length > this.max) { // color text on min/max changes
this.element.addClass('text-danger');
} else {
this.element.removeClass('text-danger');
}
}
}
Usage:
用法:
let comment = $('[name="collection-state-comment"]');
let counter = new InputCharacterCount(comment, 21, 140);
$(comment).keyup(function(event){
counter.count(event);
});
回答by ProllyGeek
You can keep your event as they are , and just use this library
您可以按原样保留您的活动,只需使用此库
Examples
例子
// applying a click event to one element
Touche(document.querySelector('#myButton')).on('click', handleClick);
// or to multiple at once
Touche(document.querySelectorAll('.myButtons')).on('click', handleClicks);
// or with jQuery
$('.myButtons').on('click', handleClicks);
回答by Shanish Singh
<script type="text/javascript">
$(document).ready(function () {
maxlength("TextArea1");
});
function maxlength(id) {
$('#' + id).on('input propertychange', function () {
CharLimit(this, 20);
});
}
function CharLimit(input, maxChar) {
var len = $(input).val().length;
if (len > maxChar) {
$(input).val($(input).val().substring(0, maxChar));
}
}
</script>