-
Notifications
You must be signed in to change notification settings - Fork 1
/
jquery-simple-txt-counter.js
73 lines (65 loc) · 2.37 KB
/
jquery-simple-txt-counter.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
/**
* jQuery Simple Text Counter
*
* @homepage https://github.com/hugosbg/jquery-simple-txt-counter#readme
* @author Hugo Gomes <[email protected]>
* @version 0.1.6
* @license MIT
*/
;(function ($) {
$.fn.simpleTxtCounter = function (options) {
const settings = $.extend({
after: undefined,
maxLength: undefined,
countText: undefined,
countElem: '<div/>',
lineBreak: true
}, options);
const counter = (input, length, max, uniqueId) => {
const { after, countText, countElem } = settings;
let count = countText ? `${countText} ${length}` : length;
if (max) {
count += ` / ${max}`;
}
const wrap = $(countElem).attr('id', uniqueId).text(count);
const parent = input.closest(after);
if (parent.length) {
let elem = parent.next('[id^=simple-txt-counter]');
if (elem.length) {
elem.text(count);
} else {
parent.after(wrap);
}
} else {
let elem = input.next('[id^=simple-txt-counter]');
if (elem.length) {
elem.text(count);
} else {
input.after(wrap);
}
}
}
return this.each(function (key) {
const input = $(this);
const max = parseInt(input.attr('maxlength') || settings.maxLength);
const uniqueId = `simple-txt-counter-${key}`;
counter(input, this.value.length, max, uniqueId);
input.on('input', function () {
counter(input, this.value.length, max, uniqueId);
if (this.value && max) {
if (settings.lineBreak === false) {
this.value = this.value.replace(/(\r\n|\n|\r)/gm, " ").slice(0, max);
} else {
this.value = this.value.slice(0, max);
}
}
}).on('keypress', function (event) {
const keyCode = event.which || event.keyCode;
if (settings.lineBreak === false && keyCode === 13) {
event.preventDefault();
return false;
}
})
});
};
}(jQuery));