Cipher
Cipher

Reputation: 45

JQuery character limiter while ignoring spaces in a textarea

I've researched on various JQuery plugins to limit the number of characters that a user may type on a text area but I haven't really found one that ignores spaces. I tried modifying an existing character counter with a limiter by using $('textarea').val().replace(/ /g,'').length and it does work. However, when the code reaches the limit, I want it such that the user won't be able to type anything more to the text area. However, it doesn't really work that way.

Here is the code to the plugin:

(function ($) {
$.fn.extend({
    limiter: function (limit, elem) {
        $(this).on("keyup focus", function () {
            setCount(this, elem);
        });

        function setCount(src, elem) {
            var chars = src.value.replace(/ /g,'').length;
            if (chars > limit) {
                src.value = src.value.substr(0, limit);
                chars = limit;
            }
            elem.html(limit - chars);
        }
        setCount($(this)[0], elem);
    }
});
})(jQuery);

I think that the problem lies with src.value = src.value.substr(0, limit); since the limit variable would still count the spaces as characters. Being a beginner with JQuery, I'm not really sure how to handle this.

Any help would really be appreciated. Thanks in advance!

Here is a fiddle with what I have so far: http://jsfiddle.net/dxUsK/1/

This is the link to the original plugin: http://www.scriptiny.com/2012/09/jquery-input-textarea-limiter/

Upvotes: 3

Views: 2158

Answers (1)

Brombomb
Brombomb

Reputation: 7076

The problem lies in the fact that your regex is removing the space characters from the string, then when you set the source value you have dropped all the space characters. A simple fix is to count the number of spaces, and then include that in the string length.

// Count the number of space characters.
var spaces = src.value.split(' ').length - 1; // remove 1 for index 0 later
if (chars > limit) {
    src.value = src.value.substr(0, limit + spaces); // Don't forget the spaces here!

There are a few other ways to do this as well, but that's a general idea.

Upvotes: 2

Related Questions