javascript (jquery) numeric input: keyCode for '3' and '#' are the same

前端 未结 4 1972
面向向阳花
面向向阳花 2021-01-17 23:33

I need to set up an so that it will accept only numeric chars, backspace, delete, enter, tabs and arrows.

There\'s a lot o

4条回答
  •  走了就别回头了
    2021-01-18 00:02

    How about something like this. This should cover cut/paste and also rmb content. We monitor the textbox for any change in content. Then we use a regex to filter out characters based on a whitelist. This won't handle non-character key, but I think that is okay.

    The \d flag says that only digits should be accepted.

    http://jsfiddle.net/UXeva/1

    $('#myTextBox').bind('input propertychange', function() {
        var text = $(this).val();
        if (isNaN(text)) {
           $(this).val(text.replace(/[^\d]/gi, ''));
        }
    });
    

    We bind to two events here. input for FireFox and propertychange for other browsers.

提交回复
热议问题