Using the Enter Keypress Event in Visualforce to Search or Change Checkbox Properties

19 Dec

Perform common actions like run a search or check a checkbox when the enter key is pressed, instead of form submission. The example below shows how to do this with help from jQuery in the Visualforce page.

Things to notice:

  • jQuery.noConflict() prevents conflicts with other javascript that Salesforce may have loaded.
  • j$(document).ready will run the contained JavaScript after the components are loaded on the page. Binding event handling to elements could be missed without this.
  • event.keyCode == 13 is the key code for the Enter button.
  • CSS classes are used to attach the keypress event handling, but you could also specify element types, names, or any other valid selector logic.
  • searchFilter CSS class could be used on text, drop down/picklists, checkboxes, etc.
  • .trigger(‘click’) is used below. It is similar to .click(), and they are interchangeable for this example. The difference that I’m aware of is .trigger(‘click’) can accept additional parameters.
  • Probably only one or two of the methods below would be used in a real project. Multiple options are documented to illustrate different options.