Skip to content

Instantly share code, notes, and snippets.

@Macagare
Created January 10, 2013 13:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Macagare/4502095 to your computer and use it in GitHub Desktop.
Save Macagare/4502095 to your computer and use it in GitHub Desktop.
JavaScript: Limit the number of characters in a textarea
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!-- Code source: http://www.devcurry.com/2009/08/limit-number-of-characters-in-textarea.html THANKS -->
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Limit Number of Characters in a TextArea</title>
<script type='text/javascript'
src='http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js'></script>
<script type='text/javascript'>
$(document).ready(function() {
$('#ta').keyup(function() {
var len = this.value.length;
if (len >= 150) {
this.value = this.value.substring(0, 150);
}
$('#charLeft').text(150 - len);
});
});
</script>
</head>
<body>
<textarea id="ta" cols="20" rows="8"></textarea><br/>
(Maximum characters: 150)<br/>
<span id="charLeft"> </span> Characters left
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment