需要启用键盘的空格键

时间:2014-10-30 04:21:51

标签: javascript jquery

我正在使用此代码禁用特殊字符,并且它正常工作但不允许在其中添加空间

提前致谢

<!DOCTYPE html>
<html>
<head>
</head>
<body>
    Alphanumeric value:
    <input type="text" id="text1" onkeypress="return IsAlphaNumeric(event);" ondrop="return false;"
        onpaste="return false;" />
    <span id="error" style="color: Red; display: none">* Special Characters not allowed</span>
    <script type="text/javascript">
        var specialKeys = new Array();
        specialKeys.push(8); //Backspace
        specialKeys.push(9); //Tab
        specialKeys.push(46); //Delete
        specialKeys.push(36); //Home
        specialKeys.push(35); //End
        specialKeys.push(37); //Left
        specialKeys.push(39); //Right
        function IsAlphaNumeric(e) {
            var keyCode = e.keyCode == 0 ? e.charCode : e.keyCode;
            var ret = ((keyCode >= 48 && keyCode <= 57) || (keyCode >= 65 && keyCode <= 90) || (keyCode >= 97 && keyCode <= 122) || (specialKeys.indexOf(e.keyCode) != -1 && e.charCode != e.keyCode));
            document.getElementById("error").style.display = ret ? "none" : "inline";
            return ret;
        }
    </script>
</body>
</html>

2 个答案:

答案 0 :(得分:2)

这是一个说明解决方案的jsFiddle。

jsFiddle

JavaScript代码变为:

var specialKeys = new Array();
specialKeys.push(8); //Backspace
specialKeys.push(9); //Tab
specialKeys.push(46); //Delete
specialKeys.push(36); //Home
specialKeys.push(35); //End
specialKeys.push(37); //Left
specialKeys.push(39); //Right
function IsAlphaNumeric(e) {
    var keyCode = e.keyCode == 0 ? e.charCode : e.keyCode;
    var ret = ((keyCode == 32) || (keyCode >= 48 && keyCode <= 57) || (keyCode >= 65 && keyCode <= 90) || (keyCode >= 97 && keyCode <= 122) || (specialKeys.indexOf(e.keyCode) != -1 && e.charCode != e.keyCode));
    document.getElementById("error").style.display = ret ? "none" : "inline";
    return ret;
}

诀窍是允许keyCode等于32。

答案 1 :(得分:0)

为空格添加特殊键值。

是32岁。

也可以参考其他人: -

http://css-tricks.com/snippets/javascript/javascript-keycodes/