Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
33
rated 0 times [  40] [ 7]  / answers: 1 / hits: 22040  / 10 Years ago, sat, march 29, 2014, 12:00:00

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


More From » textarea

 Answers
25

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


[#71713] Thursday, March 27, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
harrisonnelsonb

Total Points: 63
Total Questions: 112
Total Answers: 97

Location: Kazakhstan
Member since Mon, Sep 26, 2022
2 Years ago
;