有一个快速的方法来设置HTML文本输入(<input type=text />),只允许数字击键(加上'.')?


当前回答

我可能有另一个(简单的)解决办法…

因为String.fromCharCode(key)在QWERTY键盘上返回奇怪的东西(数字键盘返回代码为g表示1,1表示&字符..

我已经意识到,在输入中捕获keyup的最终值,将其重置为任意值是一个更简单,轻量级和防bug的方法(也可以通过一些regex…为了保持小数等等……不需要过滤其他Ctrl, Home, Del和Enter事件…)

使用jq:

<input class='pn'>
<script>
function pn(el){nb=el.value;if(isNaN(nb) || nb<1)el.value=1;}
jQuery('.pn').keyup(function(){pn(this);});
</script>

Onkeyup属性:

<input onkeyup='positiveNumericInput(this)'>
<script>function positiveNumericInput(el){nb=el.value;if(isNaN(nb) || nb<1)el.value=1;}</script>

其他回答

这里的大多数答案都有使用关键事件的缺点。

许多答案会限制你使用键盘宏进行文本选择、复制+粘贴和更多不必要的行为,其他的似乎依赖于特定的jQuery插件,这是用机关枪杀苍蝇。

这个简单的解决方案似乎最适合我跨平台,不管输入机制(击键,复制+粘贴,右键单击复制+粘贴,语音到文本等)。所有文本选择键盘宏仍然可以工作,它甚至会限制通过脚本设置非数字值的能力。

function forceNumeric(){
    var $input = $(this);
    $input.val($input.val().replace(/[^\d]+/g,''));
}
$('body').on('propertychange input', 'input[type="number"]', forceNumeric);

最好的方法(允许所有类型的数字-实负,实正,iinteger负,整数正)是:

$(input).keypress(function (evt){
    var theEvent = evt || window.event;
    var key = theEvent.keyCode || theEvent.which;
    key = String.fromCharCode( key );
    var regex = /[-\d\.]/; // dowolna liczba (+- ,.) :)
    var objRegex = /^-?\d*[\.]?\d*$/;
    var val = $(evt.target).val();
    if(!regex.test(key) || !objRegex.test(val+key) || 
            !theEvent.keyCode == 46 || !theEvent.keyCode == 8) {
        theEvent.returnValue = false;
        if(theEvent.preventDefault) theEvent.preventDefault();
    };
}); 

2个解决方案:

使用表单验证器(例如jQuery验证插件)

在输入字段的onblur事件期间(即当用户离开字段时)执行检查,使用正则表达式:

<script type="text/javascript">
function testField(field) {
    var regExpr = new RegExp("^\d*\.?\d*$");
    if (!regExpr.test(field.value)) {
      // Case of error
      field.value = "";
    }
}

</script>

<input type="text" ... onblur="testField(this);"/>

我对它做了一些调整,但它需要做更多的工作来符合JavaScript的奇怪方式。

function validateNumber(myEvent,decimal) {
    var e = myEvent || window.event;
    var key = e.keyCode || e.which;

    if (e.shiftKey) {
    } else if (e.altKey) {
    } else if (e.ctrlKey) {
    } else if (key === 48) { // 0
    } else if (key === 49) { // 1
    } else if (key === 50) { // 2
    } else if (key === 51) { // 3
    } else if (key === 52) { // 4
    } else if (key === 53) { // 5
    } else if (key === 54) { // 6
    } else if (key === 55) { // 7
    } else if (key === 56) { // 8
    } else if (key === 57) { // 9

    } else if (key === 96) { // Numeric keypad 0
    } else if (key === 97) { // Numeric keypad 1
    } else if (key === 98) { // Numeric keypad 2
    } else if (key === 99) { // Numeric keypad 3
    } else if (key === 100) { // Numeric keypad 4
    } else if (key === 101) { // Numeric keypad 5
    } else if (key === 102) { // Numeric keypad 6
    } else if (key === 103) { // Numeric keypad 7
    } else if (key === 104) { // Numeric keypad 8
    } else if (key === 105) { // Numeric keypad 9

    } else if (key === 8) { // Backspace
    } else if (key === 9) { // Tab
    } else if (key === 13) { // Enter
    } else if (key === 35) { // Home
    } else if (key === 36) { // End
    } else if (key === 37) { // Left Arrow
    } else if (key === 39) { // Right Arrow
    } else if (key === 190 && decimal) { // decimal
    } else if (key === 110 && decimal) { // period on keypad
    // } else if (key === 188) { // comma
    } else if (key === 109) { // minus
    } else if (key === 46) { // Del
    } else if (key === 45) { // Ins
    } else {
        e.returnValue = false;
        if (e.preventDefault) e.preventDefault();
    }
}

然后它被称为via:

$('input[name=Price]').keydown(function(myEvent) {
    validateNumber(myEvent,true);
});

Use:

<script>
    function onlyNumber(id){ 
        var DataVal = document.getElementById(id).value;
        document.getElementById(id).value = DataVal.replace(/[^0-9]/g,'');
    }
</script>
<input type="text" id="1" name="1" onChange="onlyNumber(this.id);">

如果你想在按下键后更新一个值,你可以改变onChange为onKeypress, onKeyDown或onKeyup。但是事件onKeypress不会在任何浏览器中运行。