Limiting Number Of Lines And Letters In Single Line In Textarea
Solution 1:
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;
returnfalse;
}
//\n count for 1 char;
charCount += 1;
});
var theLine = lines[line];
return theLine.length < maxChars;
}
});
});
Edit
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.
Solution 2:
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')) returnfalse;
} else {
if (lines[currentLine - 1].length >= $(this).attr('cols')) {
returnfalse; // prevent characters from appearing
}
}
});
});
HTML:
<textarearows="10"cols="15"></textarea>
Solution 3:
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')) {
returnfalse; // prevent characters from appearing
}
}
Solution 4:
A little late, but i made this plugin https://github.com/luisdalmolin/jquery-limitLines.
Can be usefull sometimes.
Post a Comment for "Limiting Number Of Lines And Letters In Single Line In Textarea"