Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
264 views
in Technique[技术] by (71.8m points)

javascript - Max lines textarea

I have found some scripts that limit the lines used in a textarea like this:

 $(document).ready(function(){

        var lines = 10;
        var linesUsed = $('#linesUsed');
        var newLines=0;

        $('#rev').keydown(function(e) {

            newLines = $(this).val().split("
").length;
            linesUsed.text(newLines);

            if(e.keyCode == 13 && newLines >= lines) {
                linesUsed.css('color', 'red');
                return false;
            }
            else {
                linesUsed.css('color', '');
            } 
        }); 

It works fine when you hit enter and limits it to 10 .But the problem occurs when you type sentences that are so long they automatically go to a new line without the and when you copy paste a text, then it fails to limit the lines used.

does anyone know how to fix this.

Important: solution needs to work for a textarea

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could try doing it using this logic:

JS :

var limit = 3; // <---max no of lines you want in textarea
var textarea = document.getElementById("splitLines");
var spaces = textarea.getAttribute("cols");

textarea.onkeyup = function() {
   var lines = textarea.value.split("
");

   for (var i = 0; i < lines.length; i++) 
   {
         if (lines[i].length <= spaces) continue;
         var j = 0;

        var space = spaces;

        while (j++ <= spaces) 
        {
           if (lines[i].charAt(j) === " ") space = j;  
        }
    lines[i + 1] = lines[i].substring(space + 1) + (lines[i + 1] || "");
    lines[i] = lines[i].substring(0, space);
  }
    if(lines.length>limit)
    {
        textarea.style.color = 'red';
        setTimeout(function(){
            textarea.style.color = '';
        },500);
    }    
   textarea.value = lines.slice(0, limit).join("
");
};

Here is the UPDATED DEMO


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...