1

How can i read total characters in specific line ?

i want user only will enter 75 chars in textarea with 5 lines only , means user can only use 5 enters or return, after 5 enter or return he will not be able to enter more chars. so 15 chars in one line.

i can get the current line number with following code, how about calculating total chars in that line onkeypress ?

function getLineNumber()
{
    var t = $("#textareaId")[0];
    console.log(t.value.substr(0, t.selectionStart).split("\n").length);
}​
4

2 回答 2

3

这是jsFiddle,这里是代码:

function getLineNumber()
{
    var t = $("#textareaId")[0];
    var lineIndex = t.value.substr(0, t.selectionStart).split("\n").length-1;

    //alert the characters in line
    alert(t.value.substr(0, t.selectionStart).split("\n")[lineIndex].length);
}

$("#textareaId").keypress(function() {
  getLineNumber();
});

另一种方法是在这个更新的jsfiddle1

function getLineNumber()
{
    var t = $("#textareaId").val().split("\n");
    var lineIndex = (t.length)-1
    alert(t[lineIndex].length);
}

$("#textareaId").keypress(function() {
  getLineNumber();
});

希望这可以帮助。

于 2012-09-23T18:04:00.630 回答
0

也许您可以添加一点 CSS 来解决您的问题?

选项 a:无滚动条,文本区域扩展:

textarea {
overflow:auto;
}

选项 b:没有滚动条,文本区域保持不变:

textarea {
overflow:hidden;
}

这有帮助吗?

于 2012-09-23T20:47:57.137 回答