Created
March 13, 2012 15:48
-
-
Save nicolechung/2029519 to your computer and use it in GitHub Desktop.
jQuery: Limit a textarea
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
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