Gravity Forms – How to count characters without spaces

Gravity Forms uses a jQuery character count plugin called ‘jQuery Textarea Characters Counter Plugin v 2.0’ to handle the character counting and associated functions for form fields.

The plugin lives in a file located at \wp-plugins\gravityforms\js\jquery.textareaCounter.plugin.js

The code below is a copy of this plugin, but has been adapted to only count characters and not spaces.

To implement you need to replace this code with the copy on your Gravity Forms install.

Please note: because we are replacing a file you will need to replace the file each time you update Gravity Forms.

Download: jquery.textareaCounter.plugin.js (right-click -> save as)

/*
 * jQuery Textarea Characters Counter Plugin v 2.0
 * Examples and documentation at: http://roy-jin.appspot.com/jsp/textareaCounter.jsp
 * Copyright (c) 2010 Roy Jin
 * Version: 2.0 (11-JUN-2010)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 * Requires: jQuery v1.4.2 or later
 */
(function($){
    $.fn.textareaCount = function(options, fn) {
        var defaults = {
            maxCharacterSize: -1,
            originalStyle: 'originalTextareaInfo',
            warningStyle: 'warningTextareaInfo',
            warningNumber: 0,
            displayFormat: '#input characters | #words words'
        };

        var options = $.extend(defaults, options);

        var container = $(this);

        $("<div class='charleft'>&nbsp;</div>").insertAfter(container);


        //create charleft css
        var charLeftCss = {
            'width' : container.width()
        };

        var charLeftInfo = getNextCharLeftInformation(container);
        charLeftInfo.addClass(options.originalStyle);
        //charLeftInfo.css(charLeftCss);


        var numInput = 0;
        var maxCharacters = options.maxCharacterSize;
        var numLeft = 0;
        var numWords = 0;

        container.bind('keyup', function(event){limitTextAreaByCharacterCount();})
                 .bind('mouseover', function(event){setTimeout(function(){limitTextAreaByCharacterCount();}, 10);})
                 .bind('paste', function(event){setTimeout(function(){limitTextAreaByCharacterCount();}, 10);});

        limitTextAreaByCharacterCount();

        function limitTextAreaByCharacterCount(){
            charLeftInfo.html(countByCharacters());

            //function call back
            if(typeof fn != 'undefined'){
                fn.call(this, getInfo());
            }
            return true;
        }

        function countByCharacters(){
            var content = container.val();
            var contentLength = content.replace(/\s/g, "").length;
            
            var term = "\\s*(?:\\S\\s*){0,"+options.maxCharacterSize+"}"; // RegEx - unlimited spaces, characters up to set character limit
            var rgxp = new RegExp(term, "g");  // query for characters to character limit, excluding spaces
            var xxx = content.match(rgxp) ? content.match(rgxp) : ' ' ; //  get characters to amount
            var rgxp2 = new RegExp(" ", "g");  // query to count spaces in set amount
            var contentSpaceCount = String(xxx).match(rgxp2) ? String(xxx).match(rgxp2).length : 0;   // count spaces in amount 
            
            //Start Cut
            if(options.maxCharacterSize > 0){ 
            var num = options.maxCharacterSize + contentSpaceCount;
                //If copied content is already more than maxCharacterSize, chop it to maxCharacterSize.
                if(contentLength >= options.maxCharacterSize) {
                    content = content.substring(0, options.maxCharacterSize + contentSpaceCount);
                }

                var newlineCount = getNewlineCount(content);

                // newlineCount new line character. For windows, it occupies 2 characters
                var systemmaxCharacterSize = options.maxCharacterSize - newlineCount;
                if (!isWin()){
                     systemmaxCharacterSize = options.maxCharacterSize
                }
                if(contentLength > systemmaxCharacterSize ){
                    //avoid scroll bar moving
                    var originalScrollTopPosition = this.scrollTop;
                    container.val(content.substring(0, systemmaxCharacterSize + contentSpaceCount));
                    this.scrollTop = originalScrollTopPosition;
                }
                charLeftInfo.removeClass(options.warningStyle);
                if(systemmaxCharacterSize - contentLength <= options.warningNumber){
                    charLeftInfo.addClass(options.warningStyle);
                }

                numInput = container.val().replace(/\s/g, "").length + newlineCount;
                if(!isWin()){
                    numInput = container.val().replace(/\s/g, "").length;
                }

                numWords = countWord(getCleanedWordString(container.val()));

                numLeft = maxCharacters - numInput;
            } else {
                //normal count, no cut
                var newlineCount = getNewlineCount(content);
                numInput = container.val().replace(/\s/g, "").length + newlineCount;
                if(!isWin()){
                    numInput = container.val().replace(/\s/g, "").length;
                }
                numWords = countWord(getCleanedWordString(container.val()));
            }

            return formatDisplayInfo();
        }

        function formatDisplayInfo(){
            var format = options.displayFormat;
            format = format.replace('#input', numInput);
            format = format.replace('#words', numWords);
            //When maxCharacters <= 0, #max, #left cannot be substituted.
            if(maxCharacters > 0){
                format = format.replace('#max', maxCharacters);
                format = format.replace('#left', numLeft);
            }
            return format;
        }

        function getInfo(){
            var info = {
                input: numInput,
                max: maxCharacters,
                left: numLeft,
                words: numWords
            };
            return info;
        }

        function getNextCharLeftInformation(container){
                return container.next('.charleft');
        }

        function isWin(){
            var strOS = navigator.appVersion;
            if (strOS.toLowerCase().indexOf('win') != -1){
                return true;
            }
            return false;
        }

        function getNewlineCount(content){
            var newlineCount = 0;
            for(var i=0; i<content.length;i++){
                if(content.charAt(i) == '\n'){
                    newlineCount++;
                }
            }
            return newlineCount;
        }

        function getCleanedWordString(content){
            var fullStr = content + " ";
            var initial_whitespace_rExp = /^[^A-Za-z0-9]+/gi;
            var left_trimmedStr = fullStr.replace(initial_whitespace_rExp, "");
            var non_alphanumerics_rExp = rExp = /[^A-Za-z0-9]+/gi;
            var cleanedStr = left_trimmedStr.replace(non_alphanumerics_rExp, " ");
            var splitString = cleanedStr.split(" ");
            return splitString;
        }

        function countWord(cleanedWordString){
            var word_count = cleanedWordString.length-1;
            return word_count;
        }
    };
})(jQuery);

Tagged in

2 comments on “Gravity Forms – How to count characters without spaces

  1. Hi, awesome script!

    To update this though, there is no need to hack core Gravity Forms files as updates will reset this file. You just need to deregister the original script and load your own one.

    Save the file in this article to your themes folder, then in the functions.php of your theme add the following code:

    add_action(‘gform_enqueue_scripts’, ‘replace_character_counter’, 5);
    function replace_character_counter() {
    wp_deregister_script(‘gform_textarea_counter’);
    wp_register_script(‘gform_textarea_counter’, get_stylesheet_directory_uri().’/jquery.textareaCounter.plugin.js’, array(‘jquery’));
    }

  2. Is there a way to count characters as part of a product price calculation? If they type ABC into a text field, I’d like the product to multiply times 3.

    Great script btw!

Leave a Reply to cwagoner Cancel reply

Your email address will not be published. Required fields are marked *