Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for linebreaks in textarea with jQuery

I want something like a counter for every linebreaks in a textarea. This is used when uploading a huge number of webbanners, so i need a simple counter for how many a user has added. Right now the counter works only when a user presses a link with a special bannersize.

This is my code as it is right now:

var i = 0;

$('.size').click(function(){
$('#total-number').text(i++);
return false;
});
like image 549
Simon Nielsen Avatar asked Jun 22 '10 13:06

Simon Nielsen


2 Answers

Utilize the String split function...

var text = $('#total-number').text();
var eachLine = text.split('\n');

alert('Lines found: ' + eachLine.length);

for(var i = 0, l = eachLine.length; i < l; i++) {
  alert('Line ' + (i+1) + ': ' + eachLine[i]);
}
like image 138
Josh Stodola Avatar answered Nov 03 '22 20:11

Josh Stodola


Using regular expressions, your problem can be solved like this (searching the textarea for the new line character "\n")):

//assuming $('#total-number') is your textarea element
var text = $('#total-number').val();
// look for any "\n" occurences
var matches = text.match(/\n/g);
// count them, if there are any
var breaks = matches ? matches.length : 0;

breaks variable now contains number of line breaks in the text.

like image 30
Martin Tóth Avatar answered Nov 03 '22 20:11

Martin Tóth