Skip to content

Instantly share code, notes, and snippets.

@hbrandl
Last active December 20, 2015 06:59
Show Gist options
  • Save hbrandl/6089591 to your computer and use it in GitHub Desktop.
Save hbrandl/6089591 to your computer and use it in GitHub Desktop.
jquery fallback function in case a browser doesn't support the maxlength attribute for textareas
/* jquery fallback function in case a browser doesn't support the maxlength attribute for textareas */
/*
based on code by http://that-matt.com/2008/07/textarea-maxlength-with-jquery/
*/
function count_chars(textarea){
var max = parseInt(textarea.attr('maxlength'));
textarea.parent().find('.charsRemaining').html('<b>' + (max - textarea.val().length) + '</b> characters remaining.');
}
/* fallback jquery function in case a browser doesn't support the maxlength attribute for textareas
be sure to set the attribute in the html code e.g. <textarea maxlength=255></textarea>
*/
$(document).ready(function(){
$('textarea[maxlength]').keyup(function(){
var max = parseInt($(this).attr('maxlength'));
if($(this).val().length > max){
$(this).val($(this).val().substr(0, $(this).attr("maxlength")));
}
count_chars($(this));
});
/* call count_chars once after loading the document to ensure it updates the text if there is already some text present in the textarea */
count_chars($('textarea[maxlength]'));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment