Skip to content

Instantly share code, notes, and snippets.

@willbroderick
Last active December 28, 2015 20:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save willbroderick/7560183 to your computer and use it in GitHub Desktop.
Save willbroderick/7560183 to your computer and use it in GitHub Desktop.
Show the number of remaining characters beside any text input (requires jQuery)
<script>
$(function(){
$('textarea[maxlength], input[maxlength]').bind('keyup change paste', function(){
var maxlength = parseInt($(this).attr('maxlength'));
var val = $(this).val();
var currLen = val.length;
var newLines = val.match(/(\r\n|\n|\r)/g);
if(newLines != null) {
currLen += newLines.length;
}
if(currLen > maxlength) {
$(this).val($(this).val().substr(0, maxlength));
currLen = maxlength;
}
$(this).next('.chars-remaining').children('.count').html(maxlength - currLen);
}).after('<div class="chars-remaining">Characters remaining: <span class="count"></span></div>').trigger('change');
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment