簡體   English   中英

限制jquery中動態textarea的換行數

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM