6

I have an textarea with attribute wrap="hard", meaning I should be able to get the line break (new lines) after submit to server - this works. But what I wanna do is get the new lines that are created before submission.

Why? Because I wanna count the rows that are currently visible. And now I'm NOT talking about carriage return rows. I'm talking about rows that are created by limiting the width (or setting the cols attribute) of the textarea.

I have this textbox:

<textarea id="myarea" name="myarea" cols="35" rows="10" wrap="hard">
  Some example text here. Hello my name is something I should be able to blabla.
</textarea>

Output in browser:
Some example text here. Hello my name is
something I should be able to blabla.

rows = 2

I've tried:
$('#myarea').html().split("\n").length
$('#myarea').val().split("< br>").length
$('#myarea').val().split("\r").length
And a few more combinations...

But none works. Is what I'm asking even possible without writing a script that counts each character and then creates a newline? I was hoping this would happend "automatically"...

If this is not possible, why can the server interpret (find) the new lines, while I can not?

Thanks!

4

2 回答 2

2

似乎没有内置工具来获得这个值。但是我们可以计算出来。假设 textarea 中的 line-height 是一个已知值(您可以在 css 中显式定义它)。所以计算行数的代码如下:

    var area = $('#myarea').get(0);

    //save the initial height of textarea
    var initialHeight = area.style.height;

    //set the height to 0 so scrollHeight will always return dynamic height
    area.style.height = '0px';

    //here we assume that the line-height equals to 15
    var numberOfRows = Math.floor(area.scrollHeight / 15);

    //restore textarea height
    area.style.height = initialHeight;

    console.log(numberOfRows);

工作示例http://jsfiddle.net/J5UpF/

更新

刚刚用我的代码找出了 Chrome 中的错误。我没有考虑出现在textarea右侧的滚动条。这会导致有时计算错误的行数。然而,它在 Firefox 中就像一个魅力。为了解决这个问题,我们必须计算滚动条宽度的差异并相应地调整 textarea 的宽度:

var area = $('#myarea').get(0);
var $area = $('#myarea');

//save the initial height of textarea
var initialHeight = area.style.height;

var scrollbarWidthInitial = area.offsetWidth - area.clientWidth;

//set the height to 0 so scrollHeight will always return dynamic height
area.style.height = '0px';

var scrollbarWidth = area.offsetWidth - area.clientWidth;
var scrollbarWidthDiff = scrollbarWidth - scrollbarWidthInitial;
$area.width($area.width() + scrollbarWidthDiff);

//here we assume that the line-height equals to 15
var numberOfRows = Math.floor(area.scrollHeight / 15);

//restore textarea height
area.style.height = initialHeight;
$area.width($area.width() - scrollbarWidthDiff);

console.log(numberOfRows);

更新示例http://jsfiddle.net/J5UpF/3/

更新 2

在 Chrome 中发现了一个新的令人敬畏的错误!使用placeholder属性时,Chrome 会计算占位符文本的行数。解决方法很简单:在 textarea 中输入一些数据时只需备份占位符属性,并在清除数据时恢复它。

更新示例http://jsfiddle.net/J5UpF/4/

于 2013-05-26T14:28:44.933 回答
-1

您可以在提交按钮 onClick 上绑定 jquery,然后使用

$('#myarea').val().split("\n").length
于 2013-05-26T13:41:36.647 回答