Skip to content

Instantly share code, notes, and snippets.

@stefbowerman
Created January 7, 2014 18:28
Show Gist options
  • Save stefbowerman/8304117 to your computer and use it in GitHub Desktop.
Save stefbowerman/8304117 to your computer and use it in GitHub Desktop.
Event handler for typing into inputs and textareas with a 'maxlength' attribute. Enforces a character limit on the frontend and displays a character count when approaching the maximum.
$ ->
# Binds to all inputs with a 'maxlength' attribute
# Enforces the limit and will update & hide/show an element to the user to tell them how close they are the to the limit
# the maxlength attribute is valid in HTML5 but not supported in all browsers
# Eg. <span id="my-display" class="char-count-display"></span> <input type="text" maxlength="20" data-count-display="my-display" />
ignore = [8,9,13,33,34,35,36,37,38,39,40,46]
eventName = 'keyup'
$(document).on eventName, 'textarea[maxlength], input[maxlength]', (e) ->
$self = $(this)
maxlength = $self.attr('maxlength')
code = e.which
$countDisplay = $( '#' + $(this).data('count-display') ) || false
if (maxlength && maxlength > 0) || $.inArray(code, ignore) is not -1
warningValue = parseInt maxlength * 0.70 # only show the indicator when they're within ~30% of the max
inputtedCharacterCount = $self.val().length
# continue with this keystroke if maxlength not reached
return false unless inputtedCharacterCount <= maxlength
if $countDisplay
if inputtedCharacterCount > warningValue
$countDisplay.fadeIn() unless $countDisplay.is(':visible')
else
$countDisplay.fadeOut() if $countDisplay.is(':visible')
$countDisplay.html "#{inputtedCharacterCount} / #{maxlength}"
return true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment