Adding enter key event listener to form tag for performing custom JS actions

This snippet will help to bind the enter key press to perform custom actions.

Hope this helps.

<apex:page controller="apexController">
<script>
window.onload = function()
{
var formElement = document.querySelector("[id$='pageForm']");
if(formElement.addEventListener)
formElement.addEventListener("keypress", function(e)
{
if(e.keyCode === 13)
{
// do stuff
SearchJS();
e.preventDefault();
}
}, false);
else if(formElement.attachEvent)
formElement.attachEvent("onkeypress", function(e)
{
if(e.keyCode === 13)
{
// do stuff
SearchJS();
return e.returnValue = false;
}
});
}
</script>
<apex:form id="pageForm">
<apex:actionFunction action="{!doSearch}" name="SearchJS" reRender="resultTable, ErrorPanel" status="SearchingStatus" />
<!-- Rest of the form -->
</apex:form>
</apex:page>
view raw JSactions.htm hosted with ❤ by GitHub


Comments