Forms com poucos Enters

Num projecto em JSF implementar o seguinte requisito : o formulário só deve ser submetido ao escolher umas das acções (botões/links) disponíveis..

Isto é o contrário de: se um campo de texto estiver seleccionad

o o formulário é submetido se carregarmos a tecla enter.
Isto acontece para campos com a tag input; não acontece por exemplo para a textarea.

Um requisito óbvio (usabilidade) é que o site continue a ser navegável com teclas. Logo, inputs do tipo submit e button, bem como todas as outras tags, deveriam continuar a processar o enter.

Eis a solução final, testada em FF2 e IE6:

<html>
  <head>
    <title>This form doesn't submit with Enter key</title>
  </head>
  <body>
    <form id="formID" .../>
       ...
    </form>
  
    <script type="text/javascript"><!--

/* Checks if enter key was pressed and this is allowed.
 * This functions tries to solve issue : "If a text field has focus, the 
 * form will submit upon hitting the enter (or return) key."
 * @param e the event
 * @return true if enter key  is pressed for input fields (input tags not of 
 * type 'button' or 'submit') ; false otrhewise
 */
function disableEnterKeyForInputs(e){

  // next lines suport multibrowser
  var key = (window.event) ? event.keyCode : e.which;
  var srcElement = (window.event) ? event.srcElement : e.target;
  
  if (key == 13) {
    var tagName = srcElement.tagName.toUpperCase();
    if ( tagName == 'INPUT' ) {
       // only inputTags have enter issue
       // and buttons and submit should respond to enter
       switch ( srcElement.type.toUpperCase() ){
         case 'BUTTON' :
         case 'SUBMIT' :
            return true;
          break;
         default :
            return false;
       }
    }
  }
  return true;
}

if ( (theForm = document.getElementById("formID") ) != null)   
  theForm.onkeypress=disableEnterKeyForInputs;

// -->
    </script>
  </body>
</html>

tanx to Ricardo Antunes, Lurdes Spínola

Leituras

2 thoughts on “Forms com poucos Enters”

Leave a Reply to Ruben Badaró Cancel reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>