我有一个 JS 函数,可以检查和限制输入表单中输入的某些字符。代码如下所示:
var alphaOnly = /[sA-Za-z\söÖäÄüÜ]/g;
var alphaextraOnly = /[A-Za-z\-&/'"\öÖäÄüÜ]/g;
var alphadigitsOnly = /[sA-Za-z\söÖäÄüÜ\s1234567890]/g;
var digitsOnly = /[1234567890]/g;
var integerOnly = /[0-9\.]/g;
var mailOnly = /[a-z\.@]/g;
function restrictCharacters(myfield, e, restrictionType) {
if (!e) var e = window.event
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
var character = String.fromCharCode(code);
// if they pressed esc... remove focus from field...
if (code==27) { this.blur(); return false; }
// ignore if they are press other keys
// strange because code: 39 is the down key AND ' key...
// and DEL also equals .
if (!e.ctrlKey && code!=9 && code!=8 && code!=36 && code!=37 && code!=38 && (code!=39 || (code==39 && character=="'")) && code!=40) {
if (character.match(restrictionType)) {
return true;
} else {
return false;
}
}
}
当我onkeypress
像这样添加到输入时它会起作用:
<input type="text" class="span4 register_input" id="firma" name="firma" onkeypress="return restrictCharacters(this, event, alphaOnly);" />
但我想getElementById
在脚本中做到这一点。我试图添加这个:
window.onload = function() {
document.getElementById("firma").onkeypress = restrictCharacters(this, event, alphaOnly);
}
但它没有用......请帮助。