I have a <textarea> element. Can I use JavaScript to detect that there are (for example) 10 rows of text in it?
I have a <textarea> element. Can I use JavaScript to detect that there are (for example) 10 rows of text in it?
Assuming you know the line-height, the simplest way to do this would be:
function numOfLines(textArea, lineHeight) {
var h0 = textArea.style.height;
ta.style.height = 'auto';
var h1 = textArea.scrollHeight;
textArea.style.height = h0;
return Math.ceil(h1 / lineHeight);
}
The trick here is to set the height to auto first. Then when you access scrollHeight the browser will do the layout and return the correct height including any line wraps. Then restore the textarea height to its original value and return the result.
You can get the actual text height from Element.scrollHeight, but to get the correct height, there has to be a scroll, which means you can temporarily set the text box height to 0, until you get the scroll height value then restore back the CSS height.
One you have that, you calculate the number of lines based on the CSS line-height property value (1 line of text contributes to getComputedStyle(ref).lineHeight pixels), something like...
function getTextareaNumberOfLines(textarea) {
var previous_height = textarea.style.height, lines
textarea.style.height = 0
lines = parseInt( textarea.scrollHeight/parseInt(getComputedStyle(textarea).lineHeight) )
textarea.style.height = previous_height
return lines
}
Note: your elements must be present in the DOM in order to get the scrollHeight, lineHeight heights etc. If not already present, add them, calculate the values, then remove them from the DOM.
function countLines(area,maxlength) {
// var area = document.getElementById("texta")
// trim trailing return char if exists
var text = area.value.replace(/\s+$/g, "")
var split = text.split("\n")
if (split.length > maxlength) {
split = split.slice(0, maxlength);
area.value = split.join('\n');
alert("You can not enter more than "+maxlength.toString()+" lines");
}
return false;
}
this is a simple and tested one
The simple way:
var lines = document.querySelector("textarea").value.split(/\r\n|\r|\n/).length;