How to handle the ENTER keypressed to trigger an onBlur() event?
I have an iPad webapp with a big <form>
at some point. Ev开发者_JAVA百科ery input in it has functions controlling the values, both on keyUp and Blur events.
Thing is, if the user accidentaly hits the "GO" button while typing (considered as an "enter" keypress), the form is submitted. I would like to intercept this comportment and trigger the onBlur() event of the focused element instead.
For now I have this:
load(){
document.addEventListener("keydown",logPressedKeys,false);
}
/**
* logs the keys hit in the console, will eventually trigger my onBlur event
*/
function logPressedKeys(e) {
console.log(e.keyCode);
if (e.keyCode==13) {
console.log('Enter spotted: prevent!');
e.preventDefault();//Shall prevent submitting
return false;//Hoping it prevents default if above fails
}
}
Do you guys have any advice/idea/improvement about that?
Nota bene: There has to be at least one input focused for the iPad's keyboard to pop.
Found out that document.activeElement works out in iPad's Safari.
function logPressedKeys(e) {
console.log(e.keyCode);
if (e.keyCode==13) {
e.preventDefault();
console.log('Enter spotted: prevent!');
temp=document.activeElement;
//console.log(temp);
temp.onblur();
return false;
}
return true;
}
This will not work in every browser.
document.addEventListener("keydown",logPressedKeys,false);
Use like this:
document.onkeydown = function (e) {
alert(e.keyCode);
}
精彩评论