Skip to content

Instantly share code, notes, and snippets.

@micah1701
Last active December 10, 2015 00:49
Show Gist options
  • Save micah1701/4354295 to your computer and use it in GitHub Desktop.
Save micah1701/4354295 to your computer and use it in GitHub Desktop.
Set the maximum character count of a form field with jQuery, providing the user with a visual count and stripping any values entered greater than the predetermined amount.
<div>
<textarea id="myTextarea" class="lengthcount" maxlength="150"></textarea>
</div>
<div>
<input type="text" id="myInput" class="lengthcount" maxlength="40">
</div>
<script type="text/javascript">
function charCount(element)
{
var current_len = element.val().length,
max_len = element.attr("maxlength"),
content = element.val(),
label = element.attr("id")+"_count_label";
if( current_len > max_len )
{
element.val( content.substring(0,max_len));
current_len = max_len;
}
if( $("#"+label).length == 0)
{
element.parent().append("<div id=\""+label+"\"></div>");
}
$("#"+label).html( current_len +" of "+max_len +" characters.");
}
$(document).ready(function(e) {
$(".lengthcount").each(function(){
charCount( $(this));
$(this).keyup( function(){ charCount( $(this) ) } )
});
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment