如何在我的陷阱中仅允许输入“+”和“()”来输入数字?

时间:2013-09-18 09:17:22

标签: javascript jquery

我现在的代码中,我只能输入整数。我想要做的是添加“+”和括号“()”。如何调整代码?

<script type="text/javascript">
    $(".numeric").keydown(function (event) {
        var num = event.keyCode;
        if ((num>  95 && num < 106) || (num > 36 && num < 41) || num == 9) {
           return;
         }
        if (event.shiftKey || event.ctrlKey || event.altKey) {
            event.preventDefault();
        } else if (num != 46 && num != 8) {
            if (isNaN(parseInt(String.fromCharCode(event.which)))) {
                event.preventDefault();
            }
        }
});
</script>

1 个答案:

答案 0 :(得分:1)

从表格参考 - https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent

DOM_VK_OPEN_PAREN   0xA8 (168)  Open parenthesis ("(") key.
DOM_VK_CLOSE_PAREN  0xA9 (169)  Close parenthesis (")") key.
DOM_VK_PLUS         0xAB (171)  Plus ("+") key. 

所以你的支票将是:

if ((num>  95 && num < 106) || (num > 36 && num < 41) || num == 9 || (num >=  168 && num <= 169) || num == 171)

修改

在一些帮助下,我最终创建了正则表达式来满足这些要求:

http://jsfiddle.net/elen/R8M7K/7/

代码:

$(".numeric").keydown(function (event) {
    var num = event.keyCode;
    if(event.shiftKey) num = 's_'+num;
    var pattern2 = new RegExp(/^(9[6-9]|10[0-5]|3[7-9]|40|9|s_57|s_48|171|107|s_187|)$/);
    if ( pattern2.test(num) ){
        return;
    }
    if (event.shiftKey || event.ctrlKey || event.altKey) {
        event.preventDefault();
    } else if (num != 46 && num != 8) {
        if (isNaN(parseInt(String.fromCharCode(event.which)))) {
            event.preventDefault();
        }
    }
});