![](/img/trans.png)
[英]Limit number of lines in textarea and Display line count using jQuery
[英]Limit the number of newline of dynamic textarea in jquery
我試圖限制可以在動態textarea中輸入的換行符數量,但是我編寫的代碼無法正常工作。 我需要設置用戶可以設置的至少4條換行符。 另外,我將maxlength設置為40個字符。
這是我的代碼。
$(document).ready(function(){
$("[name='memo[]']").each(function(){
$(this).keydown(function() {
newLines = $(this).val().split("\n").length;
$(this).text(newLines);
if(e.keyCode == 13 && newLines >= 4) {
alert("Exceed");
return false;
}
});
});
});
嘗試這個:
$(document).ready(function() {
$("[name='memo[]']").each(function() {
var textarea = $(this);
textarea.attr('maxlength', 40);
textarea.keydown(function(e) {
var newLines = textarea.val().split(/\r*\n/).length;
if (e.keyCode === 13 && newLines >= 4) {
e.preventDefault();
}
});
});
});
更新 :不要發出警報,代碼可以正常工作。 演示鏈接是: http : //jsfiddle.net/bobkhin/nJWk2/
使用以下示例代碼獲取文本區域中的行,然后嘗試...
String.prototype.lines = function() { return this.split(/\r*\n/); }
String.prototype.lineCount = function() { return this.lines().length; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.