Count the Number of Words in a TextArea using jQuery

If you were looking out for a script to count the number of words in a TextArea, then here it is:

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title>Count Words in a TextArea</title>

<
script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
</
script>

<
script type="text/javascript">
$(function() {
$("#btnCount").click(function() {
var strText = jQuery.trim($('#txtArea').val());
alert('Total No of Words are: ' + strText.split(/\s+/).length);
});
});
</script>
</
head>
<
body>
<
div>
<
textarea id="txtArea" cols="20" rows="10">
</
textarea>
<
br />
<
input id="btnCount" type="button" value="Count Words" />
</
div>
</
body>
</
html>

OUTPUT

image

See a Live Demo






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

1 comment:

Anonymous said...

Thanks!! after many many tries, jQuery.trim($('#txtArea').val()) works for me!