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 :D
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)">
.key?e.value = e.value-1to remove the last character: the-operator is for numeric subtraction. You can usee.value = e.value.slice(0,-1)to remove the last character, but removing the last character isn't actually appropriate given that the cursor may not be at the end of the string (user may be inserting characters in the middle).