Sha256: 387880abe7a9c92dd8fd1d534ebf228a457f00938919adf00d5598f8fe45e945
Contents?: true
Size: 1.97 KB
Versions: 3
Compression:
Stored size: 1.97 KB
Contents
(function ($) { $.fn.characterCounter = function(){ return this.each(function(){ var $input = $(this); var $counterElement = $input.parent().find('span[class="character-counter"]'); // character counter has already been added appended to the parent container if ($counterElement.length) { return; } var itHasLengthAttribute = $input.attr('data-length') !== undefined; if(itHasLengthAttribute){ $input.on('input', updateCounter); $input.on('focus', updateCounter); $input.on('blur', removeCounterElement); addCounterElement($input); } }); }; function updateCounter(){ var maxLength = +$(this).attr('data-length'), actualLength = +$(this).val().length, isValidLength = actualLength <= maxLength; $(this).parent().find('span[class="character-counter"]') .html( actualLength + '/' + maxLength); addInputStyle(isValidLength, $(this)); } function addCounterElement($input) { var $counterElement = $input.parent().find('span[class="character-counter"]'); if ($counterElement.length) { return; } $counterElement = $('<span/>') .addClass('character-counter') .css('float','right') .css('font-size','12px') .css('height', 1); $input.parent().append($counterElement); } function removeCounterElement(){ $(this).parent().find('span[class="character-counter"]').html(''); } function addInputStyle(isValidLength, $input){ var inputHasInvalidClass = $input.hasClass('invalid'); if (isValidLength && inputHasInvalidClass) { $input.removeClass('invalid'); } else if(!isValidLength && !inputHasInvalidClass){ $input.removeClass('valid'); $input.addClass('invalid'); } } $(document).on('turbolinks:load', function(){ $('input, textarea').characterCounter(); }); }( jQuery ));
Version data entries
3 entries across 3 versions & 1 rubygems