Problem:
I am trying to limit number of lines AND letters in each line in a textbox.
What i got so far:
So far i managed t
Tested in chrome : http://jsfiddle.net/3e3EH/1/
$(document).ready(function(){
var textArea = $('#foo');
var maxRows = textArea.attr('rows');
var maxChars = textArea.attr('cols');
textArea.keypress(function(e){
var text = textArea.val();
var lines = text.split('\n');
if (e.keyCode == 13){
return lines.length < maxRows;
}
else{
var caret = textArea.get(0).selectionStart;
console.log(caret);
var line = 0;
var charCount = 0;
$.each(lines, function(i,e){
charCount += e.length;
if (caret <= charCount){
line = i;
return false;
}
//\n count for 1 char;
charCount += 1;
});
var theLine = lines[line];
return theLine.length < maxChars;
}
});
});
As jbabey pointed out, ctrl+v or right-click -> paste can be an issue. right click can easily be prevented. for ctrl+v, you probable can detect it too... Just disabling javascript will obviously break the thing, too. Anyways, as any client-side validation, you have to double check on server-side.
Here's what I came up with. Fairly clean and seems to work for all the tests I can give it.
JavaScript:
$(function () {
$('textarea').on('keypress', function (event) {
var text = $('textarea').val();
var lines = text.split("\n");
var currentLine = this.value.substr(0, this.selectionStart).split("\n").length;
console.log(lines);
console.log(currentLine);
console.log(lines[currentLine - 1]);
if (event.keyCode == 13) {
if (lines.length >= $(this).attr('rows')) return false;
} else {
if (lines[currentLine - 1].length >= $(this).attr('cols')) {
return false; // prevent characters from appearing
}
}
});
});
HTML:
<textarea rows="10" cols="15"></textarea>
DEMO
Instead of looping over each line get the current line number of your cursor and check only the character length of that line. See this SO answer for implementation details.
Then change your else statement to look like this:
else{
var currLine = getLineNumber();
if (lines[currLine].length >= $(this.attr('cols')) {
return false; // prevent characters from appearing
}
}
A little late, but i made this plugin https://github.com/luisdalmolin/jquery-limitLines.
Can be usefull sometimes.