I'm trying to write a function that counts characters in a <textarea>. My current problem is to trigger an alert in my function so I can know I'm on the right track. What do I need to add to my JS to get the alert to work?

<!doctype html>
<html> <head> <title> Counter </title> 
<script type="text/javascript">  
var maxChar = 251;
var currentNum = 0;
var textarea_that_holds_the_characters_to_count = document.getElementById('ta');
calcCharacters.onkeydown = calcCharacters2;
function count_the_characters_in_the_ta_textarea() {
alert( "I'm gonna count those chars in ta!" );
     //calculation of the number of characters in <textarea>;
} 
</script>  
</head> <body>
<form>
    <textarea name="ta" rows="6" style="width:340px;"> </textarea>
	<br>
    <input type="text" name="countDisplay" size="3" maxlength="3" value="250"> Characters Remaining
</form>
</body> </html>

Recommended Answers

All 9 Replies

Hi niche1,

According to your explanation I think that all you need is an event listener in your textarea tag.

so, from what youre trying to do it should look something like this.

<textarea name="ta" rows="6" style="width:340px;" onkeypress="test()"> </textarea>

onkeypress="[some javascript function for callback]"

This reference might also be useful. http://www.w3schools.com/tags/tag_textarea.asp

In your case your code should be like this.

<textarea name="ta" rows="6" style="width:340px;" onkeypress="count_the_characters_in_the_ta_textarea()"> </textarea>

Except, that's exactly what I'm trying to avoid. I'm told I can keep my html that simple (I've added an id to the <form> tag) and do all the magic in the <script>.

I've played around with this and got access to the function.

My new problem is how to think about making the calculations in the function. What do you recommend? Here's the work so far:

<!doctype html>
<html> <head> <title> Counter </title> 

</head> <body>
<form id="ta">
    <textarea  name="ta" rows="6" style="width:340px;"> </textarea>
	<br>
    <input type="text" name="countDisplay" size="3" maxlength="3" value="250"> Characters Remaining
</form>
<script type="text/javascript">  

var maxChar = 251;
var currentNum = 0;
var calcCharacters = document.getElementById('ta');
calcCharacters.onkeydown = calcCharacters2;
function calcCharacters2 () {
alert( "I'm gonna count those chars in ta!" + calcCharacters );
     //calculation of the number of characters in <textarea>;
} 
 
</script>  
</body> </html>

So, let me get this clear, from this point on, you don't want to add anything else to the html tags?

After doing some playing around,here's what you could do.
First of all, you don't really need to refer to the form tag.
You're really just interested in the textarea. So, give the textarea the id of "ta"
Then, based on your "calcCharacters.onkeyup = calcCharacters2;" (Which I found to be a little weird statement, I don't fully understand this but I see what it does) (The order seems to go like this: Go to the calcCharacters2 function first based on the trigger event on the selected element.)

I've modified the following in your code.

<textarea  id ="ta" name="ta" rows="6" style="width:340px;"> </textarea>
calcCharacters.onkeyup = calcCharacters2;
//calcCharacters.value.length grabs the value of the textarea and reurns the length of that string. 
alert( "I'm gonna count those chars in ta!" + calcCharacters.value.length);

Hope that solves your issue.

OK. Thanks! Then how do I get the value from the var called calcCharacters into the value of the <input> and displayed in the input box generated by the <input>?

<!doctype html>
<html> <head> <title> Counter </title> 

</head> <body>
<form >
    <textarea  id="ta" name="ta" rows="6" style="width:340px;"> </textarea>
	<br>
    <input id="ta2" type="text" name="countDisplay" size="3" maxlength="3" value="248"> Characters Remaining
</form>
<script type="text/javascript">  

var maxChar = 255;
var currentNum = 0;
var calcCharacters = document.getElementById('ta');
calcCharacters.onkeydown = calcCharacters2;
function calcCharacters2 () {
var x = calcCharacters.value.length;
alert( "I'm gonna count those chars in !" + x);
     //calculation of the number of characters in <textarea>;
} 
 
</script>  
</body> </html>

Niche1,

In the document head:

onload = function(){
	var ta = document.forms[0]['ta'];
	var taCount = document.forms[0]['taCount'];
	var maxChar = 6;
	ta.onkeyup = function() {
		this.value = this.value.substr(0, maxChar);
		taCount.value = maxChar - this.value.length;
	}
};

And in the body:

<form>
	<textarea name="ta" rows="6" style="width:340px;"></textarea>
	<br>
	<input type="text" name="taCount" size="3" maxlength="3" value="" disabled="disabled"> Characters Remaining
</form>

maxChar is set to 6 for testing.

Airshow

generic counter, accepts parameters for all items, enable more than one field to be counted on a form, hate hard-coding :)

function countChars(textboxID, displayInID, maxCount){
var count = max - document.getElementById(textbox).value.length;
if (count < 5) { document.getElementById(counter).innerHTML = "<span style=\"color: red;\">" + count + "</span>"; }
else { document.getElementById(counter).innerHTML = count; }}
<form>
<textarea id='ta' name="ta" rows="6" cols='40' onkeyup='countChars("ta","ta_Display","250");' style="width:340px;"></textarea>
<br>
<span id='ta_Display'>250</span> Characters Remaining
</form>

id is more useable than name
used a span instead on an input to enable color changes <5 characters remaining
If you want the count to be displayed in an input, without color highlighting, not in a span(or any other element), alter the code above ; replace lines 3 and four with this line document.getElementById(counter).value = count;

Hey AlmostBob,

Yeah I suggested using html event listeners but that's what he wants to avoid.

Niche1,

Well, now that you've got a value that is being counted in the textarea, you can now do that algorithm that will do the following logic.

"output = maxlimit - x"

then, display the output by first accessing an element with id 'ta2' and setting the value property to the output. Do this by, "document.getElementById('ta2').value = maxChar;" After you've done that, then if the maxChar reaches 0, prevent the user from typing into the textarea. (Maybe output an alert and somehow keep their last valid input)

Refer to my code if you get stuck.

<!doctype html>
<html> <head> <title> Counter </title> 

</head> <body>
<form >
    <textarea  id="ta" name="ta" rows="6" style="width:340px;"> </textarea>
	<br>
    <input id="ta2" type="text" name="countDisplay" size="3" maxlength="3" value="255"> Characters Remaining
</form>
<script type="text/javascript">  

var maxLimit = 255;
var maxChar = 0;
var oldvalue = ""; //another way to implement maxlength in textarea.
var calcCharacters = document.getElementById('ta');
calcCharacters.onkeyup = calcCharacters2;
function calcCharacters2 () {
	var x = calcCharacters.value.length;
	//alert( "I'm gonna count those chars in !" + x);
     maxChar = maxLimit - x;
	 //alert (x + ", " + maxChar);
	 if (maxChar <= 0){
	 document.getElementById('ta').value = oldvalue;
	 alert ("You've reached the maximum length of characters");
//if you output maxChar, when you paste characters  it results in a negative value.
	 document.getElementById('ta2').value = 0;
	 }
	 else {
	 //before the maxChar reaches 0, store the last valid input
	 oldvalue = calcCharacters.value;
	document.getElementById('ta2').value = maxChar;
	}
	
} 
 
</script>  
</body> </html>

Hope that helps.

I'm told I can keep my html that simple

use any of the samples given,
that work,
while you explore the esoterica, the overly complicated crap, that currently does not work, to find a simple solution
in another form, make it work before you complicate it and make it 'simple'

incidentals
'simple' solutions all add generic listeners that listen to every keypress
'complicated' solutions all add a single listener to one element

here is a simple working code for IE and alike:

<!DOCTYPE native>
<html>
<head>
	<title>a limited length textbox</title>
<style>
</style>
</head> 

<body>
    <textarea id=txt rows=6 cols=40></textarea>
    <br>
    <input id=cnt size=3 value=30>
    Characters Remaining

<script>

max=cnt.value;

txt.onkeyup = 
txt.onkeydown = function count(){ cnt.value = max - txt.value.length }
txt.onkeypress=	function(){
			if((cnt.value=max-txt.value.length)<=0){
			return false
			}
		}
</script>  
</body> </html>

Don't sweat over firefox - you can't make it happen.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.