Question

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("\n").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 \n 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

Was it helpful?

Solution

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("\n");

   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("\n");
};

Here is the UPDATED DEMO

OTHER TIPS

Well, I couldn't figure out how to calculate the height of only the text inside a textarea, so I used a contenteditable div instead. Hope you like this solution.

HTML

<div id="container">
    <div id="rev" contenteditable="true"></div>
</div>

CSS

#container {
    height:100px;
    width:300px;
    cursor:text;
    border:1px solid #000
}
#rev {
    line-height:20px;
    outline:none
}

JS

$(document).ready(function () {
    $('#container').click(function() {
        $('#rev').focus();
    });

    var limit = 3;
    var lineHeight = parseInt($('#rev').css('line-height'));

    $('#rev').keydown(function (e) {
    var totalHeight = parseInt($('#rev').height());
    var linesUsed = totalHeight / lineHeight;

        if (e.keyCode == 13 && linesUsed >= limit) {
            $('#rev').css('color', 'red');
            return false;
        } else {
            $('#rev').css('color', '');
        }
    });
});

HERE IS A DEMO YOU CAN FIDDLE WITH

MAJOR EDIT

Following the OP pointing out I actually forgot to address the most important, I updated my code. I basically removed the check for the enter key and allowed the delete and backspace keys in case the text goes over the limit as follows. You may have to fiddle around with it a little to make it fit to your exact needs.

$(document).ready(function () {
    $('#container').click(function() {
        $('#rev').focus();
    });

    var limit = 3;
    var lineHeight = parseInt($('#rev').css('line-height'));

    $('#rev').keydown(function (e) {
    var totalHeight = parseInt($('#rev').height());
    var linesUsed = totalHeight / lineHeight;

        if (linesUsed > limit) { // I removed 'e.keyCode == 13 &&' from here
            $('#rev').css('color', 'red');
            if (e.keyCode != 8 && e.keyCode != 46) return false; // I added this check
        } else {
            $('#rev').css('color', '');
        }
    });    
        
    // I added the following lines
    $('#rev').on('paste', function () { 
        if (linesUsed > limit) {
            $('#rev').css('color', 'red');
            if (e.keyCode != 8 && e.keyCode != 46) return false;
        } else {
            $('#rev').css('color', '');
        }
    });
});

UPDATED DEMO HERE

It's too much work to try to figure how many lines based on the number characters in each line and the textarea width (does the textarea have wrapping off or not? font size, different letter widths, spaces, etc...). The easiest way is to have two textareas (one visible and one not - height set to 0) with the same width and font styles and check the scroll height of the invisible textarea.

Here is an example http://jsfiddle.net/SKYt4/1/

HTML

<textarea id="visible_textarea"></textarea>
<textarea id="hidden_textarea"></textarea> <!-- hidden by setting the height to 0 -->
<div id="used_lines"></div>

CSS

textarea {line-height:16px; /* line height to calculate number of lines */
    width:150px; /* need to match width */}
#hidden_textarea {height:0px;
    padding:0px;
    border:none;
    margin:0px;
    opacity:0;}

JavaScript

$('#visible_textarea').keyup(function(){
    $('#hidden_textarea').val(this.value);
    // checking how many lines
    var lns = Math.ceil(document.getElementById('hidden_textarea').scrollHeight / parseInt($('#hidden_textarea').css('line-height')));

    if (lns > 10) {
         $('#used_lines').css('color', '#ff0000');
    }
    else {
        $('#used_lines').css('color', '');
    }

    $('#used_lines').html(lns+' lines');
});


$('#visible_textarea').change(function(){
    $(this).keyup();
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top