Faqts : Computers : Programming : Languages : JavaScript : Event handling

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

175 of 198 people (88%) answered Yes
Recently 8 of 10 people (80%) answered Yes

Entry

How can I let a FORM being submitted with the enter key?
The keydown event does not work on NN4 when the focus is on some other control on the form other tha

Feb 25th, 2000 07:17
Soham Desai, Martin Honnen,


A FORM consisting of a single INPUT TYPE="text" field (and maybe 
additionally submit buttons) is submitted when someone presses the 
enter key inside the text field.
If you want to add keyboard handling to the whole document meaning that 
pressing enter in any field and anywhere in the document submits the 
form use code alike the following:
<HTML>
<HEAD>
<SCRIPT>
if (document.layers)
  document.captureEvents(Event.KEYDOWN);
document.onkeydown =
  function (evt) {
    var keyCode = evt ? (evt.which ? evt.which : evt.keyCode) : 
event.keyCode;
    if (keyCode == 13) {
      document.aForm.submit();
      return false;
    }
    else
      return true;
  };
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="aForm" ACTION="jsInterpreter.html">
<INPUT TYPE="text" NAME="god" VALUE="Kibo">
<INPUT TYPE="submit">
</FORM>
</BODY>
</HTML>
If you just want to submit the form when enter is pressed inside text 
fields then use code alike the following:
<HTML>
<HEAD>
<SCRIPT>
if (document.layers)
  document.captureEvents(Event.KEYDOWN);
document.onkeydown =
  function (evt) {
    var keyCode = evt ? (evt.which ? evt.which : evt.keyCode) : 
event.keyCode;
    var eventTarget = evt ? evt.target : event.srcElement;
    var textField = eventTarget.type == 'text' || eventTarget.type 
== 'textarea';
    if (keyCode == 13 && textField) {
      document.aForm.submit();
      return false;
    }
    else
      return true;
  };
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="aForm" ACTION="jsInterpreter.html">
<INPUT TYPE="text" NAME="god" VALUE="Kibo">
<TEXTAREA NAME="aTextArea" ROWS="2" COLS="20">
Kibology for all.
All for Kibology.
</TEXTAREA>
<INPUT TYPE="submit">
</FORM>
</BODY>
</HTML>
If you just want some particular fields to submit when the enter key is 
pressed add an event handler for them without capturing keys on the 
document level:
<HTML>
<HEAD>
<SCRIPT>
function handleEnterSubmission (field, evt) {
  var keyCode = evt.which ? evt.which : evt.keyCode;
  if (keyCode == 13) {
    field.form.submit();
    return false;
  }
  else 
    return true;
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="aForm" ACTION="jsInterpreter.html">
<INPUT TYPE="text" NAME="god" VALUE="Kibo">
<TEXTAREA NAME="aTextArea" ROWS="2" COLS="20"
          ONKEYDOWN="return handleEnterSubmission(this, event)">
Kibology for all.
All for Kibology.
</TEXTAREA>
<INPUT TYPE="submit">
</FORM>
</BODY>
</HTML>