你可以帮我修改我的代码吗? 我有一个接受字母数字的文本框,但我想要包含一个空格键和句号..
请帮帮我..谢谢
<html>
<head>
<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
specialKeys.push(38); //Up
specialKeys.push(40); //Down
specialKeys.push(190); //Period
specialKeys.push(32); //Space
function IsAlphaNumeric(e)
{
var keyCode = e.keyCode == 0 ? e.charCode : e.keyCode;
var ret = ((keyCode >= 48 && keyCode <= 57) || (keyCode >= 65 && keyCode <= 90) || (keyCode >= 96 && keyCode <= 122) || (specialKeys.indexOf(e.keyCode) != -1 && e.charCode != e.keyCode));
document.getElementById("error1").style.display = ret ? "none" : "inline";
return ret;
}
</script>
</head>
<body>
<div id="error1" style="width:300px;background:#FF9999;border:1px solid #FF1919;height:18px;text-align:center;font-family:Verdana;font-size:10px;line-height:18px;display:none;"> ERROR : Special Characters not allowed </div><br>
<input type='text' name='customerName' style='width:400px;text-transform:uppercase' onkeypress="return IsAlphaNumeric(event);"/>
</body>
</html>
答案 0 :(得分:1)
您可以在支票上添加(keyCode == 32 || keyCode == 46)以获取接受的字符:
<html>
<head>
<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
specialKeys.push(38); //Up
specialKeys.push(40); //Down
function IsAlphaNumeric(e)
{
var keyCode = e.keyCode == 0 ? e.charCode : e.keyCode;
var ret = ((keyCode == 32 || keyCode == 46) || (keyCode >= 48 && keyCode <= 57) || (keyCode >= 65 && keyCode <= 90) || (keyCode >= 96 && keyCode <= 122) || (specialKeys.indexOf(e.keyCode) != -1 && e.charCode != e.keyCode));
document.getElementById("error1").style.display = ret ? "none" : "inline";
return ret;
}
</script>
</head>
<body>
<div id="error1" style="width:300px;background:#FF9999;border:1px solid #FF1919;height:18px;text-align:center;font-family:Verdana;font-size:10px;line-height:18px;display:none;"> ERROR : Special Characters not allowed </div><br>
<input type='text' name='customerName' style='width:400px;text-transform:uppercase' onkeypress="return IsAlphaNumeric(event);"/>
</body>
</html>
答案 1 :(得分:0)
使用RegEx验证输入,如下所示:http://jsfiddle.net/maximgladkov/exyVL/
function IsAlphaNumeric(e) {
var result = e.keyCode > 0 || /^[0-9a-zA-Z .?\/]$/.test(String.fromCharCode(e.charCode));
document.getElementById("error1").style.display = result ? "none" : "inline";
return result;
};