Writing about JavaScript the other day got me thinking about some of the other JavaScript code that has helped me solve design problems in the past. Below is a script that limits the number of characters in a text area to a maximum value and also displays the number of characters that can still be added to the text area. This is useful when text area data will be stored in a database VARCHAR field which has a 255 character maximum. It allows the user to craft their response to match the allowable length before the form is submitted.
<script type="text/javascript">
var current_count = 0;
var max_count = 255;
function textCounter(field, target) {
if (field.value.length > max_count) {
field.value = field.value.substring(0, max_count);
} else {
current_count = max_count - field.value.length;
target.value = current_count;
}
}
</script>
<form>
<p>255 character maximum,
<input readonly type="text" name="current_count" value="255" size="3" />
characters remaining.</p>
<textarea name="fieldname" cols="60" rows="4"
onkeyup="textCounter(this, this.form.current_count);"></textarea>
</form>
The textCounter script runs once after each key stroke is complete (”key up”) and takes two arguments. The first is the field being monitored, the second is the target field that will be updated with the “characters remaining” value.
Note that we don’t add 1 and subtract 1 for each keystroke. Instead we use the current field length because it is possible to paste text into the field or to select and remove more than one character with a single delete keystroke.