views:

54

answers:

3

I am making a javascript code editor online, and right now I'm doing the line count on the left side of the editor. I can't figure out how to make it so when a new line is created, it adds +1 to the line count, so each new line it it will have the line number on the left. Anyone know a good way to do this?

A: 

Count the number of \n instances in a string, and apply it recursively to the left side div that contains the numbers.

jeffkee
A: 

Check each input, if it is a \n, just + 1. Hope to see a better answer...

PeterWong
+2  A: 

You can use string.split() to split each occurrence into an array, then get the array count.

$('textarea').keyup(function() {
    if ($(this).val().lastIndexOf('\n')!=-1)
        x = $(this).val().split('\n');
    $('div').text(x.length); // This will be the line number
});​

Fiddle

http://jsfiddle.net/WkVb9/

Robert