1 /* 2 @author: Terry 3 @params: 4 feedback - the selector for the element that gives the user feedback. Note that this will be relative to the form the plugin is run against. 5 hardLimit - whether to stop the user being able to keep adding characters. Defaults to true. 6 useInput - whether to look for a hidden input named ‘maxlength‘ instead of the maxlength attribute. Defaults to false. 7 words - limit by characters or words, set this to true to limit by words. Defaults to false. 8 @license: 9 @version: 1.2 10 @changes: code tidy via Ariel Flesler and fix when pasting over limit and including \t or \n 11 */ 12 13 (function ($) { 14 15 $.fn.maxlength = function (settings) { 16 17 if (typeof settings == ‘string‘) { 18 settings = { feedback : settings }; 19 } 20 21 settings = $.extend({}, $.fn.maxlength.defaults, settings); 22 23 function length(el) { 24 var parts = el.value; 25 if ( settings.words ) 26 parts = el.value.length ? parts.split(/\s+/) : { length : 0 }; 27 return parts.length; 28 } 29 30 return this.each(function () { 31 var field = this; 32 var $field = $(field); 33 var $form = $(field.form); 34 var limit = settings.useInput ? $form.find(‘input[name=maxlength]‘).val() : $field.attr(‘maxlength‘); 35 var $charsLeft = $form.find(settings.feedback); 36 37 function limitCheck(event) { 38 var len = length(this); 39 var exceeded = len >= limit; 40 var code = event.keyCode; 41 if (!exceeded ) 42 return; 43 44 switch (code) { 45 case 8: // allow delete BackSpace BackSpace 46 case 9: // Tab Tab 47 case 17: // Next 48 case 36: // Home 49 case 35: // End 50 case 37: // 51 case 38: //Up Arrow 52 case 39: //Right Arrow 53 case 40: //Dw Arrow 54 case 46: //~ 55 case 65: //A 56 return; 57 58 default: 59 return settings.words && code != 32 && code != 13 && len == limit; 60 } 61 } 62 63 64 var updateCount = function () { 65 var len = length(field); 66 var diff = limit - len; 67 68 $charsLeft.html( diff || "0" ); 69 70 // truncation code 71 if (settings.hardLimit && diff < 0) { 72 field.value = settings.words ? 73 // split by white space, capturing it in the result, then glue them back 74 field.value.split(/(\s+)/, (limit*2)-1).join(‘‘) : 75 field.value.substr(0, limit); 76 77 updateCount(); 78 } 79 }; 80 $field.keyup(updateCount).change(updateCount); 81 if (settings.hardLimit) { 82 $field.keydown(limitCheck); 83 } 84 85 updateCount(); 86 }); 87 }; 88 89 $.fn.maxlength.defaults = { 90 useInput : false, 91 hardLimit : true, 92 feedback : ‘.charsLeft‘, 93 words : false 94 }; 95 96 })(jQuery);
时间: 2024-11-08 22:47:46