Skip to content Skip to sidebar Skip to footer

How To Limit The Number Of Rows In A Textarea

I'm trying to limit the number of rows in a textarea, in order to make sure, that the entered text fits in the layout. The maximum amount of characters per line is 83. I found seve

Solution 1:

Try This

HTML

<form><textareaonKeyPress="return charLimit(this)"onKeyUp="return characterCount(this)"rows="8"cols="40"></textarea></form><p><strong><spanid="charCount">83</span></strong> more characters available.</p>

JavaScript

<scripttype="text/javascript">var maxLength=83;
functioncharLimit(el) {
    if (el.value.length > maxLength) returnfalse;
    returntrue;
}
functioncharacterCount(el) {
    var charCount = document.getElementById('charCount');
    if (el.value.length > maxLength) el.value = el.value.substring(0,maxLength);
    if (charCount) charCount.innerHTML = maxLength - el.value.length;
    returntrue;
}
</script>

Solution 2:

http://jsfiddle.net/gtsq74zy/1/

JS:

functiongetLineNumber(textarea) {
    return textarea.value.substr(0, textarea.selectionStart).split("\n").length - 1;
}

$(function(){
    var chars = 0;
    var ln = 0;
    var lines = [];
    var check = 1;
    $('#ta').keyup(function(e){
        lines = $(this).val().split('\n');
        ln = getLineNumber($(this)[0]);
        chars = lines[ln].length;
        check = 83 - chars;
        $('#ct').text(check);        
    }).keydown(function(e){
        lines = $(this).val().split('\n');
        ln = getLineNumber($(this)[0]);
        chars = lines[ln].length;
        check = 83 - chars;
        if(chars >= 0 && e.which != 8) check--;

        if(check < 0 && e.which != 8){
            $(this).val($(this).val() + '\n');
            lines = $(this).val().split('\n');
            ln = getLineNumber($(this)[0]);
            chars = lines[ln].length;
            check = 83 - chars;
            if(chars >= 0 && e.which != 8) check--;
        }
        $('#ct').text(check);
    });
});

HTML:

<textareaid="ta"cols="85"rows="7"></textarea><br/>
Chars Left: <divid="ct">83</div>

Solution 3:

I finally found a working solution: JSFiddle JS:

var textarea = document.getElementById("splitLines");
textarea.onkeyup = function() {
var lines = textarea.value.split("\n");
for (var i = 0; i < lines.length; i++) {
    if (lines[i].length <= 16) continue;
var j = 0; space = 16;
while (j++ <= 16) {
  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);
 }
textarea.value = lines.slice(0, 6).join("\n");
};

Post a Comment for "How To Limit The Number Of Rows In A Textarea"