Created
February 5, 2012 04:50
-
-
Save jstarrdewar/1742886 to your computer and use it in GitHub Desktop.
Limit the length of a textarea tag with a little bit of jQuery.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @author John Starr Dewar | |
*/ | |
var textarea = $('textarea')[0]; | |
var $counter = $('#counter'); | |
var limit = 140; | |
$(textarea).keydown(function(event) { | |
switch (event.keyCode) { | |
case 8: | |
// backspace | |
case 46: | |
// forward delete | |
case 37: | |
// left arrow | |
case 38: | |
// up arrow | |
case 39: | |
// right arrow | |
case 40: | |
// down arrow | |
case 86: | |
// v (as in ctrl-v or command-v) | |
break; | |
default: | |
if (this.value.length == limit) { | |
event.preventDefault(); | |
} | |
} | |
}); | |
$(textarea).on('paste', function() { | |
setTimeout(function() { | |
if (textarea.value.length > limit) { | |
textarea.value = textarea.value.substr(0, limit); | |
displayLength(); | |
} | |
}, 600); | |
}); | |
$(textarea).keyup(displayLength); | |
function displayLength() { | |
if (textarea.value.length > limit) { | |
$counter.text("Too long!"); | |
} else { | |
$counter.text(limit - textarea.value.length); | |
} | |
} | |
displayLength(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- simple html to test limiting the text area length --> | |
<textarea id="tweet" cols="36" rows="4"></textarea> | |
<div id="counter"></div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here is a detailed explanation.