반응형
jquery function으로 만들어본 input 숫자만 입력받게 하는 부분입니다. 숫자와 더불어 3자리 단위로 콤마까지 자동으로 찍히게 합니다.
JavaScript 코드입니다.
(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로 예제를 만들어 직접 사용해보세요 :)
Sample1
콤마처리, 숫자값만 입력, submit시 콤마 삭제, 입력시 콤마 처리.
Sample2
콤마처리
Sample3
숫자값 제외 모든 텍스트 삭제
반응형