Develope/jQuery
jQuery기반 input 숫자만 입력받게. (+콤마처리)
친절한 웬디양~ㅎㅎ
2014. 2. 12. 17:02
반응형
jquery function으로 만들어본 input 숫자만 입력받게 하는 부분입니다. 숫자와 더불어 3자리 단위로 콤마까지 자동으로 찍히게 합니다.
JavaScript 코드입니다.
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 |
( function ($) { // 숫자 제외하고 모든 문자 삭제. $.fn.removeText = function (_v){ //console.log("removeText: 숫자 제거 합니다."); if ( typeof (_v)=== "undefined" ) { $( this ).each( function (){ this .value = this .value.replace(/[^0-9]/g, '' ); }); } else { return _v.replace(/[^0-9]/g, '' ); } }; // php의 number_format과 같은 효과. $.fn.numberFormat = function (_v){ this .proc = function (_v){ var tmp = '' , number = '' , cutlen = 3, comma = ',' i = 0, len = _v.length, mod = (len % cutlen), k = cutlen - mod; for (i; i < len; i++) { number = number + _v.charAt(i); if (i < len - 1) { k++; if ((k % cutlen) == 0) { number = number + comma; k = 0; } } } return number; }; var proc = this .proc; if ( typeof (_v)=== "undefined" ) { $( this ).each( function (){ this .value = proc($( this ).removeText( this .value)); }); } else { return proc(_v); } }; // 위 두개의 합성. // 콤마 불필요시 numberFormat 부분을 주석처리. $.fn.onlyNumber = function (p) { $( this ).each( function (i) { $( this ).attr({ 'style' : 'text-align:right' }); this .value = $( this ).removeText( this .value); this .value = $( this ).numberFormat( this .value); $( this ).bind( 'keypress keyup' , function (e){ this .value = $( this ).removeText( this .value); this .value = $( this ).numberFormat( this .value); }); }); }; })(jQuery); |
html 예제 코드입니다.
func.js에 위의 javascript코드를 넣고 저장한뒤 아래의 html로 예제를 만들어 직접 사용해보세요 :)
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 |
< script src = "http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type = "text/javascript" ></ script > < script src = "func.js" type = "text/javascript" ></ script > < script type = "text/javascript" > jQuery(function(){ $('.sample1').onlyNumber(); $('form').submit(function(){ $('.sample1').removeText(); }); $('.sample2').numberFormat(); $('.sample3').removeText(); }); </ script > < h3 >Sample1</ h3 > < div >콤마처리, 숫자값만 입력, submit시 콤마 삭제, 입력시 콤마 처리.</ div > < form name = "frm" method = "get" actino = "index.html" > < input name = "t1" class = "sample1" type = "text" value = "10000" > < input name = "t2" class = "sample1" type = "text" value = "20000" > < button type = "submit" >submit</ button > </ form > < h3 >Sample2</ h3 > < div >콤마처리</ div > < input class = "sample2" type = "text" value = "10000" > < input class = "sample2" type = "text" value = "100000" > < h3 >Sample3</ h3 > < div >숫자값 제외 모든 텍스트 삭제</ div > < input class = "sample3" type = "text" value = "10000_abc_한글" > |
반응형