post icon

Unobtrusive javascript textarea counter using Mootools Event Class and domready Event

Here’s a cool script for using with your applications if you would like to limit the number of characters in a textarea as well as show a user how many characters they have left.

I wrote this using Mootools event and domready Event classes. For this to work you’ll need to have Mootools Event and DomReady classes. Then embed that file in the top of your document.

Feel free to use it, but if you think it’s sweet links here wouldn’t hurt… but that’s up to you! Have fun!

<script type="text/javascript">
/*Created by Darren Terhune January 16th 2008 http://headfirstproductions.ca*/
window.addEvent('domready', function() {
 //check length function
 function check_length(form) {
  max_length = 255; //set the max length of the form
  if (form.testimonial.value.length >= max_length) {
   form.testimonial.value = form.testimonial.value.substring(0, max_length);
  } else {
   form.num_left.value = max_length - form.testimonial.value.length;
  }
 }
 var testimonial = $('testimonial');
 testimonial.onkeydown = function(event) {
  check_length(this);
 };
});
</script>

Here’s my html form

<form id="testimonial" method="post" enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<p>Name (Person who gave the testimonial)</p>
<input name="name" type="text" tabindex="1" size="40" value="<?php if (isset($_POST['name'])) { echo $_POST['name']; } ?>">
<textarea tabindex="2" name="testimonial" cols="50" rows="10"><?php if (isset($_POST['testimonial'])) { echo $_POST['testimonial']; } else { echo 'Please enter the testimonial here... (max 255 characters)'; } ?></textarea><br />
<p>Characters Left</p>
<input size="3" value="255" name="num_left" id="num_left">
<input type="submit" tabindex="3" value="Submit">
<input type="hidden" name="submitted" value="TRUE">
</form>

No comments yet.

Leave a comment