开发者

Why does not IE supports my special-character blocker script in my input fields?

My script is this:

var emailmask = /^[a-z0-9.]/g;

function restrictCharacters(myfield, e, restrictionType) {
if (!e) var e = window.event
if (e.keyCode) code = e.ke开发者_开发知识库yCode;
else if (e.which) code = e.which;
var character = String.fromCharCode(code);
if (code==27) { this.blur(); return false; }
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;
    }

}
}

The input:

<input type="text" name="fx_username" value="asd" id="username" class="normal email need" onkeypress="return restrictCharacters(this, event, emailmask);"/>

It simply does not work with IE, but FF, chrome is okay. Could you help me in this case please?

Edit: The does not work means, it does not stripped the special characters like @{}¤$ß.


Your function doesn't always have a return-value.
If this condition :

if (!e.ctrlKey && code!=9 && code!=8 && code!=36 && code!=37 && code!=38 && (code!=39 || (code==39 && character=="'")) && code!=40) 

doesn't match, it will return nothing. Looks like the behaviour is different in browsers. In MSIE I think it's somehow not evaluated to false.

Solution: add this at the end of the function:

return false;


That function is incorrect in several ways.

  1. You shouldn't use var on the parameter "e" in that first line. The conventional way to write that is

    e = e || window.event;

    However, in this case it won't really work properly anyway, because the code in your "onkeypress" attribute value assumes that it can use window.event. That's incorrect and won't work in Firefox.

  2. You did not define "code" as a local variable with var.

  3. The code makes the assumption that this will be set to the element, when in fact the first parameter ("myfield") is the only thing referring to the element.

  4. If that long, long "if" test fails, the function returns undefined.

  5. The regular expression is incorrect. It matches any character at the beginning of a string, because you've got "." in the brackets. Also that "g" modifier is unnecessary. (fixed) (though I would suggest using "regexp.test(string)" instead because its probably a little faster)

It's a little hard to say what it is you want the code to do here, but until all those errors get fixed there's no clear way to say how to improve it .

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜