cForms Character Limit/Counter (without the REGEX thing)

I got quite frustrated trying to find a way to use the regex method of limiting the number of characters in a ‘multiple lines of text’ textarea in cFormsII, and I did not want to bother the awesome people that maintain the cForms homepage, cuz they get harassed enough so I went another route: jQuery.

The main problems I was having was no character count/limit, no way to insert additional HTML into the form and for some reason, when the form field contained the REGEX limit (the normal cForms recommended way), it was causing the form to not allow re-submit after a failed submit.

jQuery is awesome for stuff like this.  I added a script to my footer, next to <?php wp-footer(); ?>, in other words, right before </body>… Also, of course the whole thing needs to be contained inside of <script type=”text/javascript”>and</script> and your site needs to have already loaded jquery.js, probably in the <head> (what site doesn’t these days)

 //this first part ads an additional span, with the class 'remain', colored blue, right before the form field label,
 // which says the max characters allowed... Your selector will most likely be something other than #li--10
 jQuery( '#li--10>label' ).append( '<br><span class="remain" style="color:blue;">200</span> <span>characters remaining</span>');
 // this part counts and limits the characters
 // notice my selector is for an element with id="#cf_field_10" ...Yours will likely be different
 jQuery('#cf_field_10').keyup(function () {
 // the maximum characters you want to allow
 var maxchars = 200;
 var tlength = jQuery(this).val().length;
 jQuery(this).val(jQuery(this).val().substring(0, maxchars));
 var tlength = jQuery(this).val().length;
 remain = maxchars - parseInt(tlength);
// this final part rewrites the contents of the span.remain to how many characters are remaining as the user types
// Again, the selecter needs to be changed to fit your needs
 jQuery('#li--10>label>span.remain').text(remain);
});

 

NOTE
I may have messed up with my commenting syntax so I’ll paste the whole thing uninterrupted below.

Also, obviously, you have to be dead-on with your class/id selectors.

jQuery( '#li--10>label' ).append( '<br><span class="remain" style="color:blue;">200</span> <span>characters remaining</span>');
 jQuery('#cf_field_10').keyup(function () {
 var maxchars = 200;
 var tlength = jQuery(this).val().length;
 jQuery(this).val(jQuery(this).val().substring(0, maxchars));
 var tlength = jQuery(this).val().length;
 remain = maxchars - parseInt(tlength);
 jQuery('#li--10>label>span.remain').text(remain);
 });
 

If you found this information helpful, please consider making a donation. No amount is too small.
paypal.me/andrewapeterson

Bitcoin Donation Address:
1KAAN2ULpdZ2cjegDHYTXP1qXGLUybs5H6