You are here: irt.org | FAQ | JavaScript | Form | 7.3 | Q1775 [ previous next ]
Say you have 6 text fields in a form, each with its own "Go" button to submit the form. You want to ensure that when the user hits the Enter key while in a textbox, the corresponding "Go" button is pressed.
It involves capturing keypress events for the form, then whenever chr(13) is hit, checking if one of the textboxes has the focus. If it does, we swallow the keystroke and programatically click the corresponding button.
<script language="JavaScript"><!-- var NS = (document.layers) ? 1 : 0; var IE = (document.all) ? 1 : 0; if (NS) document.captureEvents(Event.KEYPRESS); // uncomment if you wish to cancel the key document.onkeypress = keyhandler; function keyhandler(e) { if (NS) { Key = e.which; } else { Key = window.event.keyCode; } if (Key==13) { if (document.activeElement == document.forms[0].SummStart || document.activeElement == document.forms[0].SummEnd) { document.forms[0].Summ2.click(); } else if (document.activeElement == document.forms[0].LedgStart || document.activeElement == document.forms[0].LedgEnd) { document.forms[0].Ledg2.click(); } else { return; } return false; //swallow it if we processed it } } //--></script>
Submitted by Richard Kagerer