Last active
December 10, 2015 00:49
-
-
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.
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
<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