user1290487
user1290487

Reputation: 29

get the line number with string("Line no.") from textarea?

I have used a code that show the line number from textarea and it works with me.But i would like to show a string beside that so the output will be: Line number: 3

here is the code that I have used:

http://jsfiddle.net/S2yn3/1/

and the function is:

$(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);
    });
});

Thanks guys

Upvotes: 2

Views: 1269

Answers (1)

jungos
jungos

Reputation: 506

Your code is counting the number of '\n' characters from the first character to the cursor. If you're looking for the total number of linebreaks, change...

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

to

$('#c').html('Line no. ' + this.value.split("\n").length);

Upvotes: 2

Related Questions