Getting Line Number In Text Area [duplicate]

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?

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);


​<textarea rows="6" id="t">
there is no
love in the ghetto
so come here
and get it
<input type="button" onclick="getline()" value="get line" />​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

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;

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) {

            var r = document.selection.createRange();
            if (r == null) {
                pos = 0;
            } else {

                var re = this.createTextRange(),
                rc = re.duplicate();
                rc.setEndPoint('EndToStart', re);

                pos = rc.text.length;
        $('#c').html(this.value.substr(0, pos).split("\n").length);

Here is a working example

Read More:   How to use global URLSearchParams in node

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Similar Posts