Monday, September 30, 2013

Submit a Form with the Enter Key


You've created a form in Visualforce. When pushing enter while using the form, the page refreshes instead of submitting your form. It's an easy fix with a small bit of JavaScript, which does wonders for your app's user experience.


In your Visualforce page, define this JavaScript function. It intercepts key presses on your form elements.

01<script type='text/javascript'>
02    function noenter(ev)  {
03        if (window.event && window.event.keyCode == 13 || ev.which == 13) {
04            doSearchAF();
05            return false;
06         } else {
07              return true;
08         }
09     }

Also, define this ActionFunction and tie it to your submit method in your controller.

1<apex:actionFunction name='doSearchAF' action='{!doSearch}' />

Lastly, this 'onkeypress' event should be added to every textual form element that should intercept a press of the enter key.

1<apex:inputtext value='{!settings.searchStr}' id='searchStr' styleclass='searchStr' onkeypress='return noenter(event);' />


Make sure the ActionFunction name matches up with the JavaScript function you're calling from noEnter(). When someone hits Enter, the noEnter() JavaScript function will get called, which in turn will call the doSearchAF ActionFunction, which invokes your forms submit action, in this case doSearch().

No comments:

Post a Comment