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>
<textarea onKeyPress="return charLimit(this)" onKeyUp="return characterCount(this)" rows="8" cols="40"></textarea>
</form>
<p><strong><span id="charCount">83</span></strong> more characters available.</p>
JavaScript
<script type="text/javascript">
var maxLength=83;
function charLimit(el) {
if (el.value.length > maxLength) return false;
return true;
}
function characterCount(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;
return true;
}
</script>
Solution 2:
http://jsfiddle.net/gtsq74zy/1/
JS:
function getLineNumber(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:
<textarea id="ta" cols="85" rows="7"></textarea>
<br/>
Chars Left: <div id="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"