How to limit characters inside a textarea using jQuery

Textarea characters can be limited by using few lines of jQuery code. This code also provide a counter to user how many character has been used and how many characters are remaining to type. Before looking to the code check the demo below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<html>
<head>
<script src="http://code.jquery.com/jquery-1.6.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('textarea#demotext').keyup(function() {
	var charLength = $(this).val().length; // gets number of text enntered in textarea
	$('#chCounter').html(charLength + ' of 50 characters used'); shows how many character has been used
	if($(this).val().length > 50)$('#chCounter').html('<strong>You have entered 50 characters.</strong>');
	$(this).val($(this).val().substring(0,50)); // add first 50 characters when user try to add more content
	});
});
</script>
</head>
<body>
<textarea id="demotext"></textarea>
<span id="chCounter">0 Character used</span>
</body>
</html>

The above code solves limithing the text in textarea. Please check the comments for each line to understand the code.