LNA
LNA

Reputation: 1447

Limiting word count in textarea... but when I type in the max number of words, suddenly the input text is converted to one giant string

JSFiddle: http://jsfiddle.net/qPvch/56/

The word count limit feature seems to work well. However, when I type in the max # of words (5 in the demo), and then click outside of the textarea, the words inside the text box suddenly turn into a giant string (no spaces!).

Javascript:

    var maxWords = 5;
jQuery('textarea#what').keypress(function() {
var $this, wordcount;
$this = $(this);
wordcount = $this.val().split(/\b[\s,\.-:;]*/).length;
if (wordcount > maxWords) {
    jQuery(".word_count span").text("" + maxWords);
    return false;
  } else {
    return jQuery(".word_count span").text(wordcount);
}
});

jQuery('textarea#what').change(function() {
var words = $(this).val().split(/\b[\s,\.-:;]*/);
if (words.length > maxWords) {
    words.splice(maxWords);
    $(this).val(words.join(""));
}
});

HTML:

<textarea name="what" id="what" rows="1"></textarea>
<div class="word_count">
Word count: <span></span>
</div> 

Upvotes: 0

Views: 6220

Answers (1)

Lee Meador
Lee Meador

Reputation: 12985

That problem "feature" is caused by this code (which I changed to stop it):

jQuery('textarea#what').change(function() {
var words = $(this).val().split(/\b[\s,\.-:;]*/);
if (words.length > maxWords) {
    words.splice(maxWords);
    $(this).val(words.join(" "));
}
});

But this simple change (to put a space between words) isn't really what you want.

You need something to take some words off the original string. Something like this will get in the ballpark:

if (words.length > maxWords) {
    var content = $(this).val();
    content = trimNonWords(content);
    for (var i = maxWords ; i < words.length ; ++i) {
        content = content.substring(0, content.length-words[i].length);
        content = trimNonWords(content);
    }
    $(this).val(content);
}

function trimNonWords(str) {
    ... remove any chars in the 'split' for getting word count from the end
    return result;
}

FIDDLE - Note that this fiddle has some changes are in the top part of your code too.

Upvotes: 2

Related Questions