ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • input 안에 숫자 콤마 찍기 (input numberformat, input comma)
    Web/js, jQuery 2016. 10. 18. 14:15


     


    <script type="text/javascript">

    jQuery(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);

            }

        };

        $.fn.onlyNumber = function (p) {

            $(this).each(function(i) {

                $(this).attr({'style':'text-align:left'});



                 

                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);

                });

            });

        };

        $('.numberformat').onlyNumber();

    });

    </script>




    1. 위 소스 추가

    2. 콤마찍고싶은 input 클래스에 numberformat 추가

    3. 콤마데이터 전송시 db 구성에 문제가 있을 수 있으니 submit 할때에 $('.numberformat').removeText(); 를 호출해주면 콤마를 삭제하고 데이터를 전송

    4. 감사 댓글 달기

    댓글

Designed by Tistory.