Counting and Limiting Words in a Textarea

Counting and limiting words in a textarea

Using return false to stop keyup events doesn't block the event, because in this case the event has already fired. The keyup event fires when the user releases a key, after the default action of that key has been performed.

You will need to programmatically edit the value of the textarea you have as #wordcount:

$(document).ready(function() {
$("#word_count").on('keyup', function() {
var words = 0;

if ((this.value.match(/\S+/g)) != null) {
words = this.value.match(/\S+/g).length;
}

if (words > 200) {
// Split the string on first 200 words and rejoin on spaces
var trimmed = $(this).val().split(/\s+/, 200).join(" ");
// Add a space at the end to make sure more typing creates new words
$(this).val(trimmed + " ");
}
else {
$('#display_count').text(words);
$('#word_left').text(200-words);
}
});
});

http://jsfiddle.net/k8y50bgd/

Limit words in a textarea

field.value = field.value.split(' ').splice(0, maxWords).join(' ');

update

I noticed that this also counts n spaces in a row as n-1 words, which is fixed by this:

var a = field.value.split(' ');
var words=0, i=0;
for(; (i<a.length) && (words<maxWords); ++i)
if(a[i].length) ++words;
field.value = a.splice(0,i).join(' ');

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

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.

Limit length of textarea in Words using Javascript?

If you want to prevent the typing itself (when count > 150) you can do as following:

  • Use keypress instead of keyup
  • Instead of return alert() first do an alert() and then return false;

You may also want to add change (or blur) event handler to handle text pasting.

var maxWords = 150;
jQuery('textarea').keypress(function() {
var $this, wordcount;
$this = $(this);
wordcount = $this.val().split(/\b[\s,\.-:;]*/).length;
if (wordcount > maxWords) {
jQuery(".word_count span").text("" + maxWords);
alert("You've reached the maximum allowed words.");
return false;
} else {
return jQuery(".word_count span").text(wordcount);
}
});

jQuery('textarea').change(function() {
var words = $(this).val().split(/\b[\s,\.-:;]*/);
if (words.length > maxWords) {
words.splice(maxWords);
$(this).val(words.join(""));
alert("You've reached the maximum allowed words. Extra words removed.");
}
});​

Fiddle here

How to limit the amount of words across multiple textareas?

This would be an option i guess. Just change limit to your desired need e.g 300. I left it at 3 for testing purpose. The good thing is that this way we are not disabling the keyup event handler, if we exceed the limit the words get cut off the textarea by using substr with the current value.length -1. So for example if i type 3 words in the first textarea and the limit is reached, i can still delete one word from the first textarea and type it into the second textarea, which would not be possible if we return false after limit is reached. To detect copy/paste actions i have added the paste listener and check if we've reached the limit to omit pasting more words than the actual limit of words. But pasting is still possible even across the textareas.

$(function () {
var total = 0, limit = 3, $textArea = $('textarea');
function addToTotal(collection, pastedWordCount) { var wordCount = 0; $textArea.each(function(index, element) { if (!!element.value.match(/\S+/g)) { wordCount += element.value.match(/\S+/g).length; } }); if (pastedWordCount !== undefined && pastedWordCount !== 0) { wordCount = pastedWordCount; } return wordCount; }
$textArea.on("keyup", function () { total = addToTotal($textArea); if (total > limit) { this.value = this.value.substr(0, this.value.length -1); } });
$textArea.on("paste", function (evt) { var pasteDataWordCount = 0; if (!!evt.originalEvent.clipboardData.getData('text').match(/\S+/g)) { pasteDataWordCount = evt.originalEvent.clipboardData.getData('text').match(/\S+/g).length; } total += addToTotal($textArea, pasteDataWordCount); if (total > limit) { return false; } });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><textarea name="" id="text1" cols="30" rows="10"></textarea><textarea name="" id="text2" cols="30" rows="10"></textarea><textarea name="" id="text3" cols="30" rows="10"></textarea><textarea name="" id="text4" cols="30" rows="10"></textarea>

Javascript textarea word limit

This doesn't cover all possible user actions, but I was bored and maybe you'll learn something:

HTML:

<textarea id="input_box"></textarea>

JavaScript:

function check_words(e) {
var BACKSPACE = 8;
var DELETE = 46;
var MAX_WORDS = 10;
var valid_keys = [BACKSPACE, DELETE];
var words = this.value.split(' ');

if (words.length >= MAX_WORDS && valid_keys.indexOf(e.keyCode) == -1) {
e.preventDefault();
words.length = MAX_WORDS;
this.value = words.join(' ');
}
}

var textarea = document.getElementById('input_box');
textarea.addEventListener('keydown', check_words);
textarea.addEventListener('keyup', check_words);

Try it on JS Bin: http://jsbin.com/isikim/2/edit

  • If there are 10 words in the textarea and the user presses a key, nothing will happen.
  • If a user tries to copy and paste a big chunk of text, the contents of the textarea will immediately be stripped down to just 10 words.

Actually, I'm not sure it matters that this isn't perfect. Since JavaScript runs on the client, you just need something that will work for a normal user. Malicious users can always screw with your JavaScript; no way around that. As long as you're doing real sanitation on the server, there should be no problem.



Related Topics



Leave a reply



Submit