Posts Tagged Textarea

Word count in textarea

I am showing an example for counting words in textarea. Its a very easy example and the most important part is the “countWords()” function. We are just observing the blur, keyup and focus events on textarea and when user write something in textarea the “words available” updates. You can also see its live demo here.

HTML:

<textarea rows=5cols=50id=”wc” name=”wc”>Hello World</textarea><br />
<span id=”status-ws”>100</span> words available

JavaScript:

<script type="text/javascript">
function updateWord(text, status, wordsAllow) {
	$(status).innerHTML = (+ (wordsAllow - countWords(text)));
}
 
function countWords(text) {
	show_word_count = true;
        var fullStr = text + ” “;
	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(” “);
        var word_count = splitString.length -1;
 
        if (fullStr.length <2) {
    	      return word_count = 0;
        }
 
	return word_count;
}
 
updateWord($(’wc’).value, ’status-ws’, 100);
$(’wc’).observe(blur, function(oEvent){updateWord($(’wc’).value, ’status-ws’, 100);}, false);
$(’wc’).observe(”keyup”, function(oEvent){updateWord($(’wc’).value, ’status-ws’, 100);}, false);
$(’wc’).observe(focus, function(oEvent){updateWord($(’wc’).value, ’status-ws’, 100);}, false);
</script>

Live Demo


, ,

2 Comments