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.

var j$ = jQuery.noConflict(); 
j$(document).ready(function(){
    // input field enter: trigger the search button click run the search method
    j$(document).on("keypress", ".search-filter", 
      function() { 
        if(event.keyCode == 13){ 
            j$(".searchButton").trigger('click'); 
            return false; 
        }
    });

    // input field enter: execute action function to run the search method
    j$(document).on("keypress", ".search-filter", 
      function() { 
        if(event.keyCode == 13){ 
            mySearchAF(); // run an action function or other javascript method
            return false; 
        }
    });

    // checkbox enter: simulate checkbox click event
    j$(document).on("keypress", ".selection-checkbox", 
      function() { 
        if(event.keyCode == 13){
            j$(this).trigger('click');
            return false; 
        }
    });

    // checkbox enter: change checked property without running click event
    j$(document).on("keypress", ".selection-checkbox", 
      function() { 
            if(event.keyCode == 13){
            j$(this).is(':checked') ? j$(this).prop('checked', false) : j$(this).prop('checked', true);
            return false; 
        }
    });
});