23

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?

Community
  • 1
  • 1
Freelancer
  • 9,008
  • 7
  • 42
  • 81

3 Answers3

19

This works with button click. Stolen from Find out the 'line' (row) number of the cursor in a textarea

​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" />​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
Community
  • 1
  • 1
codingbiz
  • 26,179
  • 8
  • 59
  • 96
1

You can use the following approach

  1. Find the caret position (index).
  2. Find the substring from position 0 to index
  3. Search for number of new lines in the substring obtained in step 2.

// 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/

Community
  • 1
  • 1
Joyce Babu
  • 19,602
  • 13
  • 62
  • 97
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;
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375