This repository has been archived by the owner on Jan 20, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathjquery.maxlength.js
71 lines (71 loc) · 1.84 KB
/
jquery.maxlength.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*
* jQuery Maxlength
* http://pioul.fr/jquery-maxlength
*
* Copyright 2013, Philippe Masset
* Dual licensed under the MIT or GPL Version 2 licenses
*/
(function($){
$.fn.maxlength = function(options){
var t = $(this);
t.each(function(){
options = $.extend(
{},
{
counterContainer: false,
text: '%left characters left' // %length %maxlength %left
},
options
);
var t = $(this),
data = {
options: options,
field: t,
counter: $('<div class="maxlength"></div>'),
maxLength: parseInt(t.attr("maxlength"), 10),
lastLength: null,
updateCounter: function(){
var length = this.field.val().length,
text = this.options.text.replace(/\B%(length|maxlength|left)\b/g, $.proxy(function(match, p){
return (p == 'length')? length : (p == 'maxlength')? this.maxLength : (this.maxLength - length);
}, this));
this.counter.html(text);
if(length != this.lastLength){
this.updateLength(length);
}
},
updateLength: function(length){
this.field.trigger("update.maxlength", [
this.field,
this.lastLength,
length,
this.maxLength,
this.maxLength - length
]);
this.lastLength = length;
}
};
if(data.maxLength){
data.field
.data("maxlength", data)
.bind({
"keyup change": function(e){
$(this).data("maxlength").updateCounter();
},
"cut paste drop": function(e){
setTimeout($.proxy(function(){
$(this).data("maxlength").updateCounter();
}, this), 1);
}
});
if(options.counterContainer){
options.counterContainer.append(data.counter);
} else {
data.field.after(data.counter);
}
data.updateCounter();
}
});
return t;
};
})(jQuery);