Monday, May 21, 2007

Make Enter Key submit form

Here is a simplified example of how to make a form submit when the enter key is pressed while the cursor is in a particular textfield. NOTE: It is necessary to use the onkeypress event and NOT the onkeydown event of the textfield. This is because returning false in the onkeydown event does NOT stop the form from submitting. Returning false in the onkeypress event DOES stop the form submitting which is what we need it to do. <html> <body> <form> <input type="text" name="q" > <input type="submit" name="btnG" value="Submit"> <script language="JavaScript"> function handleEnterKey() { if ((event.which && event.which == 13) (event.keyCode && event.keyCode == 13)) { document.forms[0].elements('btnG').click(); return false; } else return true; } document.forms[0].elements('q').onkeypress = handleEnterKey; </script> </form> </body> </html>

1 comment:

Anonymous said...

Chuadna madarchud