Forum Moderators: open
I'm trying to figure out how to count the number of lines (\n) in a form textarea, and then print that number to the page. It also needs to update as more lines of text are being added. (i would prefer to echo the count as plain text rather than in another textbox).
The only scripts I've been able to find count words in a textarea.
Any ideas?
[blue]<html><head>
<title>Banana</title>
<script>
function countLines()
{
var area = document.getElementById("texta")
// trim trailing return char if exists
var text = area.value.replace(/\s+$/g,"")
var split = text.split("\n")
return split.length
}
</script>
</head>
<body>
<textarea id="texta" cols="30" rows="8">
I think you could use the split function to break
the text into an array.
Then check the array's length to get
the line count.
</textarea>
<br>
<button onclick="alert(countLines())">count</button>
</body></html>[/blue]
This will only count the line breaks entered by the user.
It won't count the lines caused by wrapping.
<html><head>
<title>Banana</title>
<script>
function countLines() {
var area = document.getElementById("texta")
// trim trailing return char if exists
var text = area.value.replace(/\s+$/g,"")
var split = text.split("\n")
return split.length }
</script></head>
<body>
<textarea id="texta" cols="30" rows="8" onChange="document.all.count.innerHTML = 2000 - countLines()">
I think you could use the split function to break the text into an array.
Then check the array's length to get the line count.
</textarea><br>
<div id="count">2000</div>
</body></html>
Should I be using something other than onChange?
Seriously amended
Yes, chadmg, putting the onKeyPress ¦¦ Up on the element is good. I was about to put it on the document. Now it only fires when the textbox has focus. Also we can send a ref to the function, which will make it more efficient (useful if it runs on every key event).
<textarea onKeyPress="countLines([blue]this[/blue])"> Then the function is amended:
function countLines([blue]area[/blue])
{
// trim trailing return char if exists
var text = area.value.replace(/\s+$/g,"")
var split = text.split("\n")
return split.length
}
You could go further, and have the script only running the function when the return ky has been pressed - a few cross-browser things enter into the equation there.
You may also want to remove the bit that trims the content end
.replace(/\s+$/g,""). I don't know what you're requirements are there.