Buy Now
Sign in

FAQ search

Adding a character counter in CFv5

Details
Published: Monday, 28 July 2014 15:22

Sometimes you need to limit the number of characters that a user types into a text input or textarea. This FAQ shows you how to use a jQuery script to do that very simply.

There are many jQuery character counter scripts available, I chose to use Philippe Massett's jQuery.maxlength. The documents and a download link are here.

First download the package from GitHub using the download link. Unzip the package and find the jquery.maxlength.min.js file. You will need to upload this to a convenient folder on your site. I put my copy in the /components/com_chronoforms5/extras/Maxlength folder.

In your form Designer tab add a Textarea Box or Text Box element ; click the Edit button to open the settings and make sure that the element has an id set, I used a textarea with the id textarea1

In the Extra Params box add a maxlength attribute e.g. maxlength=50

Save the element.

In the Setup tab add a Load JavaScript action and move it up before the HTML (Render form) action if necessary.

Open the action settings and in the JS Files box add the URL to the jquery.maxlength.min.js file. In my case that was

http://my_domain.com/components/com_chronoforms5/extras/Maxlength/jquery.maxlength.min.js

In the JS Code box add this code:

jQuery(document).ready(function (jQ) {
  jQ( '#textarea1' ).maxlength();
});

Save and test the form. You should see a message "50 characters left" under the textarea.

Note: If you don't add the maxlength attribute then the script will do nothing!!

Options

There are two options that you can set 'text' to change the message; and counterContainer to specify a different location for the message. For example:

jQuery(document).ready(function (jQ) {
  jQ( '#textarea1' ).maxlength({
    text: 'You have typed %length characters of %maxlength, <span style=\'color: red; font-weight:bold;\'>%left</span> remain.'
  });
});

Events

The script will also fire a JavaScript event when the element is edited, you can use this to show messages. Here's an example that changes the color of the textarea border as the character count changes.

jQuery(document).ready(function (jQ) {
  jQ( '#textarea1' ).maxlength();
  jQ( '#textarea1' ).bind('update.maxlength', function(event, element, lastLength, length, maxLength, left){
    if ( left > 10 ) {
      element.css('border', '2px solid green');
    } else if ( left > 0 ) {
      element.css('border', '2px solid orange');
    } else {
      element.css('border', '2px solid red');
    }
  });
});