-
Notifications
You must be signed in to change notification settings - Fork 0
/
jQuery.maxlength.js
48 lines (42 loc) · 1.64 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
(function($){
/**
* 최대 글자 수, 현재 글자 수 표시
* @param {Object} options 옵션
* @return {Object} jQuery Object this;
*/
$.fn.maxlength = function (options){
var settings = $.extend(
{},
$.fn.maxlength.defaults,
options
);
var counterElm = '<span class="text-limit">' +
'<span data-val-length="target"></span>' +
'<span data-val-length="max"></span>' +
'</span>';
return this.each(function () {
var $wrap = $(this);
var $val = $wrap.find('[maxlength]');
var $parent = $wrap.find(settings.parent);
var maxLength = $val.attr('maxlength') || 'maxlength를 설정해주세요';
if (!$wrap.find('.text-limit').length) {
var val = $val.val() || '';
$parent.length ? $parent.append(counterElm) : $wrap.append(counterElm);
$wrap.find(settings.target).html(val.length);
$wrap.find(settings.maxTarget).html('/' + maxLength);
$wrap.on('keyup', settings.valName, function (e) {
var input = e.currentTarget;
var val = input.value;
if (val.length > maxLength) input.value = val.substr(0, maxLength);
$wrap.find(settings.target).html(input.value.length);
});
}
});
};
$.fn.maxlength.defaults = {
valName: '[maxlength]',
target: '[data-val-length=target]',
maxTarget: '[data-val-length=max]',
parent: '[data-val-length=parent]',
};
})(jQuery);