Limit Number of Lines in Textarea and Display Line Count Using Jquery

Limit number of lines in textarea and Display line count using jQuery

html:

<textarea id="countMe" cols="30" rows="5"></textarea>
<div class="theCount">Lines used: <span id="linesUsed">0</span><div>

js:

$(document).ready(function(){

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

$('#countMe').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', '');
}
});
});

fiddle:
http://jsfiddle.net/XNCkH/17/

Limiting number of lines in textarea

This might help (probably be best using jQuery, onDomReady and unobtrusively adding the keydown event to the textarea) but tested in IE7 and FF3:

<html>
<head><title>Test</title></head>
<body>
<script type="text/javascript">
var keynum, lines = 1;

function limitLines(obj, e) {
// IE
if(window.event) {
keynum = e.keyCode;
// Netscape/Firefox/Opera
} else if(e.which) {
keynum = e.which;
}

if(keynum == 13) {
if(lines == obj.rows) {
return false;
}else{
lines++;
}
}
}
</script>
<textarea rows="4" onkeydown="return limitLines(this, event)"></textarea>
</body>
</html>

*Edit - explanation: It catches the keypress if the ENTER key is pressed and just doesn't add a new line if the lines in the textarea are the same number as the rows of the textarea. Else it increments the number of lines.

Edit #2: Considering people are still coming to this answer I thought I'd update it to handle paste, delete and cut, as best as I can.

<html>

<head>
<title>Test</title>
<style>
.limit-me {
height: 500px;
width: 500px;
}
</style>
</head>

<body>
<textarea rows="4" class="limit-me"></textarea>

<script>
var lines = 1;

function getKeyNum(e) {
var keynum;
// IE
if (window.event) {
keynum = e.keyCode;
// Netscape/Firefox/Opera
} else if (e.which) {
keynum = e.which;
}

return keynum;
}

var limitLines = function (e) {
var keynum = getKeyNum(e);

if (keynum === 13) {
if (lines >= this.rows) {
e.stopPropagation();
e.preventDefault();
} else {
lines++;
}
}
};

var setNumberOfLines = function (e) {
lines = getNumberOfLines(this.value);
};

var limitPaste = function (e) {
var clipboardData, pastedData;

// Stop data actually being pasted into div
e.stopPropagation();
e.preventDefault();

// Get pasted data via clipboard API
clipboardData = e.clipboardData || window.clipboardData;
pastedData = clipboardData.getData('Text');

var pastedLines = getNumberOfLines(pastedData);

// Do whatever with pasteddata
if (pastedLines <= this.rows) {
lines = pastedLines;
this.value = pastedData;
}
else if (pastedLines > this.rows) {
// alert("Too many lines pasted ");
this.value = pastedData
.split(/\r\n|\r|\n/)
.slice(0, this.rows)
.join("\n ");
}
};

function getNumberOfLines(str) {
if (str) {
return str.split(/\r\n|\r|\n/).length;
}

return 1;
}

var limitedElements = document.getElementsByClassName('limit-me');

Array.from(limitedElements).forEach(function (element) {
element.addEventListener('keydown', limitLines);
element.addEventListener('keyup', setNumberOfLines);
element.addEventListener('cut', setNumberOfLines);
element.addEventListener('paste', limitPaste);
});
</script>
</body>
</html>

Limit number of textarea characters per line in Jquery

For testing:

$('#btn').on("click", function(e) {
let num = $("#splitLines").val().split('\n')
//get value and split it into new lines
console.clear()
console.log(num)
num.forEach(e => {
// for each new line
let n = e.split("")
//get number of chars
console.log(n.length)
if (n.length !== 13) {
// if some line dos not have 13:
alert("Each line needs 13 char")
} else {
// all good
console.log(true)
}
})
});

Simplified solution:

$('#btn').on("click", function(e) {
$("#splitLines").val().split('\n').forEach(e => {
e.split("").length !== 13 ? alert("Each line needs 13 char") : console.log(true)
})
});
1234567890123
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea rows="11" cols="60" name="txtarea[]" id="splitLines" value=""></textarea>
<button type="button" id="btn">test</button>

Limit number of lines (rows + Enter key press) in Text area plus show Line Count

I will not provide any code snippets for your problem but just an approach of how i'm seeing the solution. Basing your algorithm on the font.js javascript library, you could retrieve the length in pixels of the text and of all the caracters in the text. If you're using a unique font in your textbox you could know when a line is completed each time the number of pixels in a line equals or is inferior to the actual number of pixels used in a new line. In pseudo-code it would look like this :

var textBoxLineInPixels = 300 //or getting the actual number through DOM;

onChangeEvent {
var totalNumberOfPixels = getNumberOfPixelsFromElement(idToYourTextBox);
var numberOfLinesUsed = totalNumberOfPixels / textBoxLineInPixels;
update(idToYourNumberOfLinesContainer, numberOfLinesUsed);
}

Dividing the total number of pixels in your textarea by the the number of pixels in a line will give you the current number of lines used in your textarea.

How to get the number of lines in a textarea?

I have implemented the lines and lineCount methods as String prototypes:

String.prototype.lines = function() { return this.split(/\r*\n/); }
String.prototype.lineCount = function() { return this.lines().length; }

Apparently the split method will not count a carriage return and/or newline character at the end of the string (or the innerText property of a textarea) in IE9, but it will count it in Chrome 22, yielding different results.

So far I have accomodated for this by subtracting 1 from the line count when the browser is other than Internet Explorer:

String.prototype.lineCount = function() { return this.lines().length - navigator.userAgent.indexOf("MSIE") != -1); }

Hopefully someone has a better RegExp or another workaround.

Limit lines in a textarea?

have you specified <textarea maxlength="2000"></textarea> - that would be a good place to start. this would limit the characters to 2000.

You could also check for the enter key (keycode=="13" if i recollect correctly) and either a) disallow it or b) only allow it after a full stop or after e.g. >30 characters. Just a suggestion

Definitely specify the maxlength though. Then no more than that will be able to be inputted. Note that breaks count as characters and are deducted from the characters remaining.

Have a go at this and you will see.



Leave a reply



Submit