메뉴 건너뛰기

Dev tips

JavaScript 모든 브라우저에 숫자만 입력받기 적용

taknim 2011.02.24 04:27 조회 수 : 7271 추천:1799

http://jonathan.tang.name/files/js_keycode/test_keycode.htmlhttp://blog.naver.com/ecaface/140095173286jQuery 를 삽입한 후 사용
id="input1" 인 텍스트박스에 숫자만 입력 추가

event 가 가지고 있는 속성들...
var fields = ['charCode', 'keyCode', 'which', 'type', 'timeStamp',
                  'altKey', 'ctrlKey', 'shiftKey', 'metaKey'];

<script>
jQuery.fn.numeric  = function(options)
{
  var opts = $.extend(jQuery.fn.numeric.defaults, options);
  return this.each(function()
  {
    $(this).keydown(function(e)
    {
      var key = e.charCode || e.keyCode || 0;
      if (opts.allowControlKeys && jQuery.fn.numeric.isControlKey(key))
        return true;
      if (e.shiftKey || e.altKey || e.ctrlKey) return false;
      return ((key > 47 && key < 58) || (key > 95 && key < 106));
    });
  });
};
jQuery.fn.numeric.isControlKey = function(key)
{
  var controlKeys = new Array(8, 9, 46, 37, 38, 39, 40);
  return jQuery.inArray(key, controlKeys) > - 1;
}
jQuery.fn.numeric.defaults = {allowControlKeys: true};

$(document).ready(function() {
  $("#input1").numeric();
  $("#input1").css("ime-mode", "disabled");
}
</script>

http://jonathan.tang.name/code/js_keycode
-------------------------------------------------------------------------
뭐 이런 방법도 ...
-------------------------------------------------------------------------
<html>
           <head>
                      <script type="text/javascript">
                                function onlynumber(obj)
                                {
                                          var patt = /[^0-9]/g;
                                          obj.value = obj.value.replace(patt, '');
                                }
                     </script>
           </head>
           <body>
                     <input type="text" id="ssn1" onkeyup=" onlynumber (this)" style="ime-mode:disabled"/>
           </body>
</html>