-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjquery.textCounter.js
94 lines (69 loc) · 2.28 KB
/
jquery.textCounter.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/*=================================================================================================
jQuery "textareaCounter" plugin
=================================================================================================*/
(function($){
$.fn.textareaCounter = function(options) {
// setting the defaults
var defaults = {
limit: 100
, type: 'char'
, label: ''
};
/*
Options:
---------------------
limit: number
type: 'char|word' (default = char)
label: 'id|class' (for class include leading dot)
Example usage:
---------------------
$("textarea").textareaCounter({ limit: 100, type: 'word' });
*/
var options = $.extend(defaults, options);
// get the count
function getCount(obj, elmLbl, type) {
text = obj.val();
if(text === "") {
txtCount = 0;
} else {
// Word cound or Character count?
txtCount = (options.type == 'word') ? $.trim(text).split(" ").length : txtCount = $.trim(text).length;
}
if(txtCount > options.limit) {
var diff = (options.limit - txtCount);
elmLbl.text(diff+type+'remaining').css('color','red');
} else {
elmLbl.text((options.limit - txtCount)+type+'remaining').css('color','green');
}
}
// and the plugin begins
return this.each(function() {
var obj, text, txtCount, limited, uiLabel, uiCounter;
obj = $(this);
// Which label do we need?
uiLabel = (options.type == 'word') ? ' words ' : ' characters ';
if (options.label === '') {
uiCounter = $('<div class="text-counter">sdfgsdfgsdf'+options.limit + ' ' + uiLabel + 'remaining</div>');
obj.after(uiCounter);
} else {
uiCounter = $(options.label);
uiCounter.text(options.limit + ' ' + uiLabel + 'remaining');
}
$(document).ready(function() {
getCount(obj, uiCounter, uiLabel);
});
if ($.browser.msie) {
obj.keypress(function() {
getCount(obj, uiCounter, uiLabel);
});
obj.change(function() {
getCount(obj, uiCounter, uiLabel);
});
} else {
obj.keyup(function() {
getCount(obj, uiCounter, uiLabel);
});
}
});
};
})(jQuery);