Calling an apex method on press of enter key

Use following javascript along with action function to execute apex method on press of enter key.

Javascript:
<script type='text/javascript'>
function runOnEnter(ev) {
if (window.event && window.event.keyCode == 13 || ev.which == 13) {
searchAccRecs();
return false;
} else {
return true;
}
}
</script>

 
Action function:
<apex:actionFunction name="searchAccRecs" action="{!searchAcc}" reRender="pgblcktbl"/>


Lets see an example to demo this:
In the following example we want to search accounts with name that is being entered in the text box. This should happen when submitt button is pressed plus should also happen if user enters the text and presses Enter key. For this we should write a javascript as mentione dabove and call it on event of keypress for input text. Java script call the action function which intern calls the apex method.

Visualforce Page


<apex:page standardController="account" extensions="searchaccounts">
<apex:form >
<script type='text/javascript'>
function runOnEnter(ev) {
if (window.event && window.event.keyCode == 13 || ev.which == 13) {
searchAccRecs();
return false;
} else {
return true;
}
}
</script>
<apex:pageBlock >
<apex:inputText value="{!searchString}" onkeypress="return runOnEnter(event);"/>
<apex:commandButton value="Submit" action="{!searchAcc}" reRender="pgblcktbl"/>
<apex:pageBlockTable value="{!accList}" var="acc" id="pgblcktbl">
<apex:column value="{!acc.name}"/>
<apex:column value="{!acc.accountnumber}"/>
<apex:column value="{!acc.annualrevenue}"/>
<apex:column value="{!acc.Industry}"/>
<apex:column value="{!acc.AccountSource }"/>
</apex:pageBlockTable>
</apex:pageBlock>
<apex:actionFunction name="searchAccRecs" action="{!searchAcc}" reRender="pgblcktbl"/>
</apex:form>
</apex:page>


Apex Class 


public with sharing class searchaccounts {
Public List<account> accList{get;set;}
Public string searchString{get;set;}
public searchaccounts(ApexPages.StandardController controller) {
}

Public void searchAcc(){
accList = new List<account>();
accList = [select id,name,accountnumber,annualrevenue,Industry,AccountSource from account where name =: searchString limit 5];
}
}












Related Articles

1 comment:

  1. Clean up any spilled oil and pour the used oil in a container to drop off at your local recycling center.

    There is also another body, the International Lubricant Standardization and Approval Committee (ILSAC),
    jointly set-up by US and Japanese motor manufacturers, which also recommends
    motor oil grades which comply with the API standard.

    Most of the Major Brands of "Synthetic Oil" are really "Synthetic Blends".


    Also visit my web-site - Масла За Коли

    ReplyDelete