Reputation: 75
I'm trying to count textarea rows using pure javascript and I'm not sure why my selector.rows
is not return correct number of rows :(
this is my js:
var selector = document.querySelectorAll("textarea");
for(i = 0; i < selector.length; i++){
var array = selector[i];
var count = array.rows;
console.log(array, count);
if(count > 1 && count.scrollHeight < count.offsetHeight){
count--
console.log(array.rows);
}else{
count++
console.log(array.rows);
}
}
Upvotes: 2
Views: 1010
Reputation: 29655
The code above works fine, because it is designed to return the number of rows that the textbox
displays (the attribute rows
of the textarea
). But you want the number of lines that the text inside the textarea
occupies, and here is a solution for that:
height
of the textarea (I used getComputedStyle()
as the height is not defined)line-height
for the content in the textarea
(= height / rows).scrollHeight
of the textarea
.scrollHeight
by the calculated line-height
.It would be something like this:
var selector = document.querySelectorAll("textarea");
for(i = 0; i < selector.length; i++){
var txtarea = selector[i];
var count = txtarea.rows;
// get the textarea height
var cs = window.getComputedStyle(txtarea, null);
var tHeight = parseInt(cs.getPropertyValue("height"));
// calculate the line-height
var tLineHeight = tHeight / count;
// calculate the number of rows in the textarea
var tRows = Math.round(txtarea.scrollHeight / tLineHeight);
document.getElementById("results").innerHTML += "ROWS = " + tRows + "<br>";
}//end for
<textarea rows="4" cols="40">
Lorem ipsum dolor sit amet, eam ex bonorum scripserit. Audire diceret delectus ex usu. Sonet alienum duo id. Elit delenit pro ex, quo case honestatis eloquentiam ea, everti detracto intellegat no nam. Pro quodsi euismod qualisque ei. Est et modus porro, eam solet gubergren ea.
In soleat eleifend per, no per nibh mollis labitur. Sit ei possim molestiae, ius antiopam principes ei. Ea eam soleat fierent. Mel et quod veri convenire, vis no modus oporteat posidonium. Dicunt viderer vocibus his te, qui agam iriure pertinacia te. In sit homero facilisi iudicabit. Timeam eligendi sed an.
</textarea>
<textarea rows="4" cols="40">
Hello
</textarea>
<div id="results"></div>
And you can also see it in a variation of your JSFiddle: http://jsfiddle.net/qxKmW/46/ (in this case, check the console log)
One issue with this solution: it will return the higher value of these two:
textarea
; or rows
attribute (or its default value). That's why in the example above will return 4 instead of 2 for the second textarea
. A possible solution for this would be to set the rows
attribute to 1, then you'll always get the correct value.
Upvotes: 1