How to limit the number of characters entered in a text area

后端 未结 6 1369
忘了有多久
忘了有多久 2020-12-10 08:58

Here\'s my attempt at limiting the number of characters entered into a text area:

var limit = 255;
var txt = $(\'textarea[id$=txtPurpose]\');

$(txt).keyup(f         


        
6条回答
  •  清歌不尽
    2020-12-10 09:30

    My plugin:

    (function($) {
    
       $.fn.textCounter = function(options) {
    
            var defaults = {
                maxlimit: 100,      // max limit character
                description: null,  // element for descript count character
                enter: true         // if accept enter
            };
    
            var options = $.extend({}, defaults, options);
    
            if (options.description != null) {
                if (typeof options.description == 'string')
                    options.description = $('#' + options.description);
            }
    
            var fevent = function(ev) {
    
                var value = $(this).val(),
                    k = ev.charCode || ev.keyCode || ev.which,
                    incremente = 1;
    
                if (k == 8)
                    incremente = -1;
    
                if (options.enter == false && k == 13)
                    return false;
    
                if (ev.ctrlKey || ev.altKey || ev.metaKey)  //Ignore
                    return true;
    
                if ((value.length + incremente) > options.maxlimit)
                    return false;
    
                return true;
            };
    
            var fcounter = function(ev) {
                var value = $(this).val();
                $(options.description).text(options.maxlimit - value.length);
            };
    
            $(this).each(function(i, el) {
                if ($(this).is(':input')) {
                    $(this).unbind('keypress.textCounter').bind('keypress.textCounter', fevent);
                    $(this).unbind('keyup.textCounter').bind('keyup.textCounter', fcounter);
                }
            });
    
        };
    
    })(jQuery);
    

提交回复
热议问题