Suppose you have a login form and you want to send the form when user press enter on his keyboard and not only by clicking on the submit button.
This can be achieved capturing a specific event when the user is typing. We have to capture the keypress event and listen to trigger an action when the enter key is pressed.
In the html form we have to add the “onkeypress” attribute that will contain a call to a javascript fnction that to the job.
The javascript function receive also a string parameter, so you can customize and reuse this code (it’s the ‘formid’ parameter).
The “evt” and “thisObj” parameters return the event handler and the object (the input type) that made the call to the function. The event parameter is important, the object that calls the fnction is not important as parameter since it’s used only to blur the input field.
Here is the javascript function that handle the event:
<script type="text/javascript"> function submitonenter(formid,evt,thisObj) { evt = (evt) ? evt : ((window.event) ? window.event : "") if (evt) { // process event here if ( evt.keyCode==13 || evt.which==13 ) { thisObj.blur(); document.getElementById(formid).submit(); } } } </script>
This is the html form with the “onkeypress” listener:
<form id='formlogin' action='file.php' method='post'> <input type='text' name='username' /> <input name='pass' type='password' onkeypress="submitonenter('formlogin',event,this)" /> <input type='submit' value='login'/> </form>