|

Let the Users Know
How Many Characters They can still Type with JavaScript
In some application the business process
requires that users enter comments regarding reports,
data or simply the general state of business affairs.
The data is to be stored in a database somewhere and
you allow the user to enter a maximum number of characters
that correspond to the width of your database column
in the corresponding table.
Let us examine the options that are available
to accomplish the task:
1. Allow the user to enter as many characters
as they want and then cut it off in the database. This
would actually manipulate the comment without the user's
permission and thus is not an option.
2. Allow the users to
enter as many characters as they want and make the check
in the database. If the
number of characters is above your limit, send back a
message asking the user to shorten their comment. This
can be done but is very taxing to the patience of the
user because he/she has to wait a round-trip to the database
and does not know in advance how many characters are
still available.
3. Tell the users in real time how
many characters are still available for them to complete
their comment. This is our solution and what we implement
in JavaScript.
Our solutions will consists of two components.
The first component is a function that calculates how
many characters are still available. The second components
actually builds the form.
function textCounter(field,
countfield, maxlimit) {
if (field.value.length > maxlimit)
field.value =field.value.substring(0, maxlimit);
else
countfield.value = maxlimit - field.value.length;}
The next component is the actual form fields.
One is the input text field and the other displays the
remaining number of characters. The above function is
called on the onkeyup and onkeydown events
for the text box.
<textarea name="message" cols="25" rows="4" wrap="PHYSICAL" id="message"
onkeydown="textCounter(this.form.message,
this.form.remLen,50);"
onkeyup="textCounter(this.form.message,
this.form.remLen,50); "></textarea>
<input name="remLen" type="text" id="remLen" value="50" size="3" maxlength="3" readonly
/>
characters still available.
The result can be seen below and is very
helpful to the end-user. It also guarantees that you
will be able to fit the comment in a database table with
a column of maximum length 50 without having to make
a round trip to check.
By the way, this script also works in most modern
browsers as well!
next
tip |