admin管理员组

文章数量:1332896

I have an iPad webapp with a big <form> at some point. Every 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 portment 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.

I have an iPad webapp with a big <form> at some point. Every 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 portment 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.

Share Improve this question asked Jul 1, 2011 at 12:49 monsieur_hmonsieur_h 1,3801 gold badge10 silver badges20 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 2

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); 
}

本文标签: javascriptHow to handle the ENTER keypressed to trigger an onBlur() eventStack Overflow