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

帅比萌擦擦* 提交于 2019-12-01 15:51:10

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.

If older browsers are'nt an issue, the number input type should cover this.

<input type="number" />

If not you could use the isNaN javascript function

$("#number1").on('keyup', function() {
    var myval = $(this).val();
    if (isNaN(myval)) {
        alert('numbers only!');
    }
});

Personally I would do some regex filtering with a check to see if the value has changed, that will allow any character that does not change the value, like tabs, enter and arrows. With a regex you could also add or remove any character, or you could use \d for digits only or as below, [0-9]. Up to you really what your exact needs are?

var P;
$("#number2").on('keyup', function() {
    var V = $(this).val();
    if (V != P) {
        $(this).val(V.replace(/[^0-9]/g,''));
    }
    P=V;
});

They could also be combined to something like this:

$("#number3").on('keyup', function() {
    var V = $(this).val();
    if (isNaN(V)) {
        $(this).val(V.replace(/[^0-9]/g,''));
    }
});

Here's a FIDDLE to test them out!

Why not do something like this? It uses a combination of the keyup() event and isNaN(). It'll work whether the user types with the keyboard or pastes a number.

The way it works is, as soon as the text changes, it will check if the value is a number. If not, it will trim the input until it is a number. So, if you enter 25s or 25ss, you will be left with 25.

This will work with ctrl+v paste as well. It won't work with right-click paste and for that reason, I have disabled right-clicking only on the textbox.

Live Demo

The Jquery

$(document).ready(function(){
    $('#number').keyup(function(){    
        var input = this.value;
        while (isNaN(input))
        {
            input = input.substring(0,input.length-1);
            $('#number').val(input);             
        }
    });
    $('#number').bind("contextmenu",function(e){
        return false;
    });
});

jQuery also provides a shiftkey boolean on the event object:

$('#myTextBox').keydown(function(e){
  if(e.keyCode === 51 && !e.shiftKey){
     // '3' key pressed while shift was **not** held down (not '#')
  }
});

EDIT I reread your question and changed the code above for !shiftkey

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!