with the "onKeyPress " event handler I see that I can capture and examine the value of a keystroke before it is displayed on the screen. I have made good use of this for single character fields where I want to examine if the value is correct and also convert the value to upper case like so:
As I said this works great when I am only dealing with one character. But for longer strings than one character, I would like to prevent unwanted characters from becoming part of the string. Can I use this technique by intercepting what the user is typing give them an alert and then cancel that keystroke entry?
Code:
<input
type="text"
name="f1"
id ="f1"
maxLength="1"
onKeyPress="return isHorS(event);"
/>
function isHorS(evt)
{
evt = (evt) ? evt : event;
var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode : ((evt.which) ? evt.which : 0));
if (charCode != 8 && charCode != 9 && charCode != 32 && charCode != 72 && charCode != 104 && charCode != 83 && charCode != 115 )
{
alert("You must either leave blank or enter H or S!");
document.getElementById("f1").value = "";
}else{
if (charCode == 104 || charCode == 115 )
{
var cUp = String.fromCharCode(charCode)
document.getElementById("f1").value = cUp.toUpperCase();
}
}
}
Comment