Submitting a Form with the Enter Key


if (key == 13) {   document.forms[0].submit(); } 

Depending on the browser type and configuration, pressing the Enter key while in a form field does not always submit the form. Sometimes, for instance, the button that submits the form resides in another frame. In that case, adding a bit of JavaScript to ensure that the Enter key sends the form data, as well, comes in handy.

All that is necessary to implement for that functionality is the standard key event listener from the previous phrase. The key code for the Enter key is 13, so when this code is found, the form is submitted:

Submitting a Form When Enter Has Been Pressed (formsubmit.html)

<script language="JavaScript"   type="text/javascript"> function checkKey(e) {   var key;   if (window.event) {     key = window.event.keyCode;   } else {     key = e.keyCode;   }   if (key == 13) {     document.forms[0].submit();   } } window.onload = function() {   document.forms[0].elements["field"].onkeydown = checkKey; } </script> <form> <input name="field" type="text" /> </form> 




JavaScript Phrasebook(c) Essential Code and Commands
JavaScript Phrasebook
ISBN: 0672328801
EAN: 2147483647
Year: 2006
Pages: 178

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net