Skip to content

Instantly share code, notes, and snippets.

@nicolechung
Created March 13, 2012 15:48
Show Gist options
  • Save nicolechung/2029519 to your computer and use it in GitHub Desktop.
Save nicolechung/2029519 to your computer and use it in GitHub Desktop.
jQuery: Limit a textarea
jQuery(document).ready(function($) {
/*
* <textarea id="custom_excerpt">Text</textarea>
* <p id="error"></p>
*/
$('#custom_excerpt').keyup(function() {
// get the limit from the maxlength attribute
var limit = 100;
// get the current text inside the textarea
var text = $(this).val();
// count the number of characters in the text
var chars = text.length;
if (chars > limit) {
// and if there are use substr to get the text before the limit
$(this).css({
'border': '1px solid red',
'background': '#fee1e8'
});
$('p#error').html((text.length) + " letters written.");
} else {
$(this).css({
'border': 'none',
'background': '#fff'
});
$('p#error').html((limit - text.length) + " letters remaining.");
if(chars < 1 ){
$('p#error').html("No letters remaining.");
}
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment