Possible Duplicate:
Find out the 'line' (row) number of the cursor in a textarea
I want to find out the line number that a user's cursor in on in a HTML textarea
element.
Is this possible using javascript and jquery?
Possible Duplicate:
Find out the 'line' (row) number of the cursor in a textarea
I want to find out the line number that a user's cursor in on in a HTML textarea
element.
Is this possible using javascript and jquery?
这适用于按钮单击。从查找文本区域中光标的“行”(行)号中窃取
function getline()
{
var t = $("#t")[0];
alert(t.value.substr(0, t.selectionStart).split("\n").length);
}
HTML
<textarea rows="6" id="t">
there is no
love in the ghetto
so come here
and get it
</textarea>
<input type="button" onclick="getline()" value="get line" />
You can use the following approach
// Test
$(function() {
$('#test').keyup(function() {
var pos = 0;
if (this.selectionStart) {
pos = this.selectionStart;
} else if (document.selection) {
this.focus();
var r = document.selection.createRange();
if (r == null) {
pos = 0;
} else {
var re = this.createTextRange(),
rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint('EndToStart', re);
pos = rc.text.length;
}
}
$('#c').html(this.value.substr(0, pos).split("\n").length);
});
});
Here is a working example http://jsfiddle.net/S2yn3/1/
This can be split up in three steps:
I guess you don't want to consider wrapped text and scrolled content. Assuming you use the function from this answer, it would be like:
var el = document.getElementById("inputarea"); // or something
var pos = getCaret(el),
before = el.value.substr(0, pos),
lines = before.split(/\r?\n/);
return lines.length;