Featured Project - Sidewalk Photorealistic Composition
Featured Project - Dorsoduro Supermoto
Featured Project - Installing & Using Hugin, Autopano, & Enblend on Windows
Featured Project - Long Room
Featured Project - Mikuni 36mm Carburetor
Featured Project - ZBrush & Maya Self Portrait
Featured Project - Eye Scream Animation Web Site

(Jamie3D.com (This Site)) Older »

« Newer (MikeSmith3D.com)

Jan 6th 2008

JavaScript Tutorial - Counting Characters

Introduction

If you've never used JavaScript before this tutorial might scare you a bit, but I'll do my best to make it understandable. If you don't do any HTML coding, then it doesn't really apply to you, but you may like to read it anyway.

Abstract

When collecting typed user input from a HTML form, you may want certain text areas to have a maximum number of allowed characters. For single line text input, the <input> element has an attribute to limit the number of characters typed, but the <textarea></textarea> element does not. Below is an example of both, notice how the input element only accepts five characters — this is fine, since I set the limit myself.

Input Element

Textarea Element

Even though the <input> element has a built in limit, it may still be useful to let your user know how many characters they are working with. At the bottom of this page, you can see an example of this in action. When you type in the field, some simple JavaScript is executed every time a key is released, and the count of characters is displayed near the field.

In JavaScript, we often use events to trigger functions. A simple example of this is: When a user clicks an image, something happens, this would be done with an event like this: onclick="the thing that we tell JavaScript to do" similarly, the example we are going to build in a moment will use the onkeyup event. this event is triggered whenever the user releases a key while typing in that input element. (a perfect time to count how many characters there are) What we would like in the end is to display a counter, that updates every time the user releases a key.

Functions

what if we could group a set of commands together into a nice little package and then ask that little package to do something? A JavaScript function is just that. To write a function, we first create a script element:

<script type="text/javascript">
<!--



//-->
</script>

This will give us a home to place our JavaScript function. Next, we will create the function using the keyword function, followed by the function name, a pair of parentheses, and a pair of curly braces. All together, they are usually formatted like this:

<script type="text/javascript">
<!--

function count_field() {


}

//-->
</script>

The parentheses contain arguments (I like to think of them as inputs) and right now we have none. The curly braces can contain variables (I like to think of them as containers to store other information), as well as other functions and logic statements like the common if and else statements which allow us to do things if a condition is met and something else if the condition is not met.

For this function (that will count the contents of a text field) we will need 3 arguments for the function.The first will be the actual input element we are measuring, the second will be the HTML element that we send our report to, and the third will be a number representing the maximum number of characters we will accept. I'll give them the following names: input_element, report_id, and max_count respectively. Arguments are placed inside the parentheses and are separated with a comma.

<script type="text/javascript">
<!--
function count_field(input_element,report_id,max_count) {


}
//-->
</script>

Now that we have our arguments in place, we will add a variable to this function. The variable will store the number of characters in the input element for later use in our function. To create a new variable, we will use the keyword var followed by the variable name, the assignment operator (equal sign) and finally, the information we want to assign to this variable. In this case, this information is the length of the value of the field that we will receive as an argument later on. We can write this variable like this:

<script type="text/javascript">
<!--
function count_field(input_element,report_id,max_count) {

var current_count = input_element.value.length;
}
//-->
</script>

Notice that the above variable refers to the first argument. This means that whatever the first argument is, the variable will be equal to the length of the value of that argument, and this will be expressed as an integer. (1, 2, 3, 4, 5 etc.) In other words, the variable current_count is now equal to the length (in characters) of whatever we send to this function as our first argument.
We have just written the code to calculate the number of characters in a field.

However, we still have 2 more arguments that we have not accounted for. Let's handle the report_id argument next. The count of the characters is really no good to us in this case unless we can see it. So, we have created a situation where we will create a HTML element (probably a <p> or <span> element) that will display the count. We will give this element a unique id and access it though this id. The next step will be to send the var current_count to the HTML element. We'll do that like this:

<script type="text/javascript">
<!--
function count_field(input_element,report_id,max_count) {

var current_count = input_element.value.length;

document.getElementById(report_id).innerHTML = current_count;
}
//-->
</script>

Our last addition to the function is a bit easier to read if we go from right to left: The current_count will be assigned to the innerHTML (the actual content of a HTML element) of the element supplied in report_id in our document. Now, remember that report_id is the name of one of the arguments, so here we are using the second argument to figure out which HTML element our number should be sent to.

This function thus far if used correctly should show us the count of a field, but we still have one more argument to use: The max_count argument. The max_count argument is going to be a number, and we will compare this number to the current_count to determine if we have too many characters in our input element. this can be done with an if statement.

The if statement looks a lot like a function, but instead of arguments, it contains one or more conditions. we will use a simple > (greater than) operator to compare the two integers. I will also add an else statement to do something else if the condition evaluates to false.

<script type="text/javascript">
<!--
function count_field(input_element,report_id,max_count) {

var current_count = input_element.value.length;

  if(current_count > max_count) {
  document.getElementById(report_id).innerHTML = current_count + ' (too many)';
  }

  else {
  document.getElementById(report_id).innerHTML = current_count;
  }

}
//-->
</script>

In the above code, I have added quite a bit, so let's just go through step by step.

The if statement depends on weather the current_count is greater than the max_count. If the comparison evaluates to true, this would mean that there are too many characters.

Notice how the code that outputs the count to the HTML element of our choice is within the curly braces of the if statement. This means that it will only be executed if the current count is more than the max count, and in that case, I've added the text '(too many)' to the end of the line using the concatenation (string joining) operator — The Addition Symbol.

When the if statement evaluates to false, (if the current_count is less than the max_count) the code will move on to the else statement and simply output the current_count of our input element.

The completed script element will be added to the HTML page, either within the <head></head> section, or within the <body></body> itself. The function will be loaded and waiting for us when the page loads, and we can then call on this function from our HTML code.

The HTML

Thus far, we know that we need at least 2 HTML elements for this code to work: We need an <input> element and a <p> element. (for the report) The input element will have an extra bit of code to "listen" for a key release, and when that happens, it will execute our little function.

Within your HTML document's body or head, paste the script.
After the script, we need to create our P element that will hold the report of how many characters there are:

<p id="input_report"></p>

Then, we create our INPUT element. (remember that an input element is a form element and therefore must be inside of a form element)

<form name="test_form" action="#">
  <input name="test_input" type="text" />
</form>

Adding the JavaScript

Next, we add the onkeyup event to our input element like this:

<form name="test_form" action="#">
  <input name="test_input" type="text" onkeyup="count_field()" />
</form>

What the above code says (essentially) is: every time a key is released (while typing in this element), call the count_field() function. At this point the function doesn't know what field to count, where to display the result, or how many characters is too many. This is where our arguments (or inputs) come in handy.

All together the code looks like this:

<p id="input_report"></p>
<form name="test_form" action="#">
  <input name="test_input" type="text" onkeyup="count_field(this,'input_report',12)" />
</form>

Notice that a comma separates each argument here just as in our function, and that input_report is in single quotes. We need to make sure that we pass the second argument in quotes because we mean it literally, it's not the name of a function or variable or any other special JavaScript lingo, it's just the text input_report. It needs to be in single quotes because we are already inside double quotes. (for the onkeyup event.)

Below is the code in action! Note that the code can be used on the <textarea></textarea> element as well; simply place the onkeyup event in the opening <textarea> tag.

 

I hope this tutorial has been helpful to you, and if you've got any comments about it, or would like to point out an error just email me or leave a comment.

 
Loading...

Web Design © 2002 – 2009 Jamie Hamel-Smith