JSFiddle - React, Tailwind, and code Playground
HTML
<div class="word_count">
<span></span>
</div>
<textarea id="textarea1"></textarea>
CSS
textarea{
width:400px;
height:200px
}
JavaScript
var maxWords = 20;
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,\.-:;]*/);
// console.log(words.length);
if (words.length > maxWords) {
words.splice(maxWords);
$(this).val(words.join(""));
alert("You've reached the maximum allowed words. Extra words removed.");
}
// console.log(words.length);
});