?yb? 2009-06-15 09:22 采纳率: 100%
浏览 1066
已采纳

如何只允许数字(0-9)在 HTML 输入框使用 jQuery?

I am creating a web page where I have an input text field in which I want to allow only numeric characters like (0,1,2,3,4,5...9) 0-9.

How can I do this using jQuery?

转载于:https://stackoverflow.com/questions/995183/how-to-allow-only-numeric-0-9-in-html-inputbox-using-jquery

  • 写回答

28条回答 默认 最新

  • ?yb? 2012-01-19 00:17
    关注

    Have a look at this plug-in (Fork of texotela's numeric jquery plugin). This (jStepper) is another one.

    This is a link if you want to build it yourself.

    $(document).ready(function() {
        $("#txtboxToFilter").keydown(function (e) {
            // Allow: backspace, delete, tab, escape, enter and .
            if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110]) !== -1 ||
                 // Allow: Ctrl+A, Command+A
                (e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) || 
                 // Allow: home, end, left, right, down, up
                (e.keyCode >= 35 && e.keyCode <= 40)) {
                     // let it happen, don't do anything
                     return;
            }
            // Ensure that it is a number and stop the keypress
            if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
                e.preventDefault();
            }
        });
    });
    

    NOTE: If your webpage uses HTML5, you can use the built in <input type="number"> and use the min and max properties to control the minimum and maximum value.


    The following is minimized and also allows for use of <kbd>CTRL</kbd>+<kbd>X</kbd>, <kbd>CTRL</kbd>+<kbd>C</kbd>, and <kbd>CTRL</kbd>+<kbd>V</kbd>

    $(function() {
      $('#staticParent').on('keydown', '#child', function(e){-1!==$.inArray(e.keyCode,[46,8,9,27,13,110])||(/65|67|86|88/.test(e.keyCode)&&(e.ctrlKey===true||e.metaKey===true))&&(!0===e.ctrlKey||!0===e.metaKey)||35<=e.keyCode&&40>=e.keyCode||(e.shiftKey||48>e.keyCode||57<e.keyCode)&&(96>e.keyCode||105<e.keyCode)&&e.preventDefault()});
    })
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <div id="staticParent">
        <input id="child" type="textarea" />
    </div>

    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(27条)

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题