Skip to content

Instantly share code, notes, and snippets.

@ethanresnick
Created October 5, 2014 22:08
Show Gist options
  • Save ethanresnick/a45c4016216a39163c85 to your computer and use it in GitHub Desktop.
Save ethanresnick/a45c4016216a39163c85 to your computer and use it in GitHub Desktop.
Character Count Directive Base
//maxlength inputs
$.webshims.ready('DOM forms', function() {
$('input[maxlength]').each(function(i, elem) {
var $elem = $(elem);
//1. Remove maxlength attribute and replace it with a data-maxlength so that the browser will let user type beyond the maximum, which is better usability,
// but then webforms will use a custom constraint to mark the field as invalid (even wihtout maxlength) if the user tries to leave it with a value that's too long
$elem.attr('data-maxlength', $elem.attr('maxlength')).removeAttr('maxlength');
//2. Set up the character counter's HTML
$elem.add('label[for='+ $elem.attr('id') +']').wrapAll('<div class="input-maxlength wrapper" />')
.filter('label').append('<span class="remaining-chars help-text disabled">' + ($elem.attr('data-maxlength') - $elem.val().length) + '</span>');
});
//add listeners to make the character counter work
$('form').on('keyup keydown', 'input[data-maxlength]', function(e) {
var $this = $(this),
span = $('label[for='+ $this.attr('id') +']').find('span.remaining-chars'), //more reliable than .prev(label) because the stupid checkmark gets stuck in between on valid.
length = $this.prop('value').length,
maxlength = $this.attr('data-maxlength'),
remaining = maxlength-length,
warnAt = (parseInt(maxlength/34)*5);
span.html(remaining);
if(remaining <= warnAt) {
span.addClass(remaining >= 0 ? 'almost-error' : 'error').removeClass(remaining < 0 ? 'almost-error' : 'error');
}
else {
span.removeClass('almost-error error');
}
$this.trigger('refreshCustomValidityRules');
});
//add the custom validity to rule that responds to data-maxlength
$.webshims.addCustomValidityRule('maxlength', function(elem, value){
if($(elem).attr('data-maxlength') && value.length > $(elem).attr('data-maxlength')){
return true; //means it's not valid
} else {
return false; //means it's valid
}
}, 'The value you entered is too long.');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment