i have a code here triggered by an onkeypress… i want it to alert whenever there is a special character typed. Aside from an alert, if the user will type a special character in a field, the typed special character should be erased and the focus should go back to the field. I can’t seem to shake this problem. Can you help me? thanks in advance 😀
function ei(e)
{
var iChars = "!@#$%^&*()+=-[]\\\';,./{}|\":<>?";
for (var i = 0; i < e.value.length; i++) {
if (iChars.indexOf(e.value.charAt(i)) != -1) {
alert ("Please do not use special characters.");
e.value = e.value-1;
e.focus();
return false;
}
}
}
this will be called in text field.. like this
<input type="text" name="name" onkeyup="ei(this)">
Why would you bother using the
keyupevent? It’d be better off using thekeydownorkeypressevent and then cancelling it (I used this site to find the keycodes):I would also suggest you look into jQuery rather than having inline JavaScript to hook up your events and also take a look at the jQuery Validation plugin as that should help take care of a lot of your code.