function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
JimRaeJimRae 

user hitting enter key on inputfield in tabbed view

I hope someone can help me.  I have a VF page that includes 4 tabbed sections.  One of them is a custom search tab.  When the user types their criteria (an account name) into the inputtext box, and clicks my search button, everything works great.  If the user types in their criteria, then presses "Enter",  the page refreshes and takes the user back to the first tab (my search tab is the fourth tab).
How can I get pressing enter to be the same as clicking the button?

Thanks in advance!!

Jim
Best Answer chosen by Admin (Salesforce Developers) 
Rajesh ShahRajesh Shah

Found an interesting thing:

 

When the commandButton has reRender attribute associated with it, it is rendered with type="button" in html. Else it is rendered as type="submit". With submit, the enter key works fine; not with button.

 

Now if I have to make my enter key work, I have to remove rerender. This reloads the whole page and since my page has got images, the reload takes time and doesn't looks good. I need the reRender and also have to use the enter key. I tried by capturing the enter key event and clicking the button using Javascript. It executes the Action method but doesn't rerenders anything. 

 

Is there any solution for this?

All Answers

jwetzlerjwetzler
There is no way in Visualforce or in HTML to specify a default button for use with the Enter key.  By default it takes the first button rendered.  There may be some things you can do with javascript event listeners or CSS (I saw a trick somewhere where the button you want is first in the code, but you use CSS to rearrange the order on the screen) but in that case Google is going to be your friend.

Of course the easiest thing is to just make it the first button in your list :)
JimRaeJimRae
Jill,
Thanks for the quick response
It is actually the only button on my entire page.  Do the tabs act like buttons as well?  That would seem to be the behavior.  Not sure about that though.
 
Jim
jwetzlerjwetzler
Well now I'm confused.  Can you post an example?  Please use the SRC button.
JimRaeJimRae
Here you go:
 
Code:
<apex:page Controller="POVNotificationController" tabStyle="Event" sidebar="false"><!-- showheader="false"  > -->
<style>
     .activeTab {background-color: #236FBD; color:white; background-image:none}
     .inactiveTab { background-color: lightgrey; color:black; background-image:none}
  </style>
     <apex:sectionHeader Title="POV Notification System" subtitle="{!FTSActivityAccount.Name}"></apex:sectionHeader>
   <apex:pageBlock rendered="{!IF((Event==null),true,false)}">
  <apex:PageMessage strength="3" severity="info" title="Error" detail="This Event has been deleted."/>
   </apex:pageBlock>
      <apex:pageBlock title="FTS Invitees" rendered="{!IF((FTSInvitee==null),false,true)}">
       <apex:pageBlockTable value="{!FTSInvitee}" var="contact" >
      <apex:column headerValue="Invitee Name" value="{!contact.Name}"/>
      <apex:column headerValue="Invitee Title" value="{!contact.Title}"/>
      <apex:column headerValue="Invitee Phone" value="{!contact.Phone}"/>
      <apex:column headerValue="SFDC Role" value="{!contact.UserRole.Name}"/>
      </apex:pageBlockTable>
   </apex:pageBlock>
   <apex:tabPanel switchType="client" selectedTab="name2" id="theTabPanel" tabClass="activeTab" inactiveTabClass="inactiveTab">
 <apex:tab label="Account Summary" name="AccountSumStuff" id="tabAccountSum">
 <apex:pageMessages />
   <apex:pageblock title="Account Detail">
   <apex:pageBlockTable value="{!FTSActivityAccount}" var="Account">
   <apex:column value="{!Account.Name}"/>
   <apex:column value="{!Account.AccountNumber}"/>
   <apex:column value="{!Account.CMA_Verified__c}"/>
   <apex:column value="{!Account.CorpCity__c}"/>
   <apex:column value="{!Account.CorpState__c}"/>
   </apex:pageBlockTable>
   </apex:pageBlock>
   </apex:tab>
        <apex:tab label="Account Detail" name="AccountStuff" id="tabAccountDetail">
   <apex:detail subject="{!FTSActivityAccount}" title="false" relatedList="false"/>
   </apex:tab>
   <apex:tab label="Event Detail" name="EventStuff" id="tabEventDetail">
    <apex:detail subject="{!Event}" title="false" relatedList="false"/>
   </apex:tab>
         <apex:tab label="CMA Account Search" name="AccountSearch" id="tabAccountSearch">
   <apex:pageBlock title="Search Accounts"> 
   <apex:form >
 
  This will perform a wildcard search for the CMA account name specified. <br/>     
  <apex:actionStatus id="status"  >
     <apex:facet name="start">
     <img src="{!URLFOR($Resource.CFS,'image/Activityspinner.gif')}" border="0" height="18px" width="18px" /> Searching for matches....
     </apex:facet>
    </apex:actionStatus>
    <apex:inputText id="searchBox" value="{!searchText}">
    </apex:inputtext>  
   <apex:commandButton action="{!search}" value="Search" id="searchBtn" rerender="AccountSearch,data" status="status"/ >   
   <apex:pageBlockTable value="{!result}" var="acc" id="data" > 
     <apex:pageMessages />   
    <apex:column >     
     <apex:facet name="header"><b>Name</b></apex:facet> {!acc.name}    
    </apex:column>   
    <apex:column >     
     <apex:facet name="header"><b>Account Number</b></apex:facet> {!acc.AccountNumber}    
    </apex:column>
    <apex:column >     
     <apex:facet name="header"><b>Site Number</b></apex:facet> {!acc.SiteNumber__c}    
    </apex:column>   
    <apex:column >     
     <apex:facet name="header"><b>Corp. City</b></apex:facet> {!acc.CorpCity__c}    
    </apex:column>   
    <apex:column >     
     <apex:facet name="header"><b>Corp. State</b></apex:facet> {!acc.CorpState__c}    
    </apex:column>   
   </apex:pageBlockTable> 
  </apex:form>
 </apex:pageBlock>
   </apex:tab>
   </apex:tabpanel>
   </apex:page>

CONTROLLER:
public class POVNotificationController {
    event masterevent;
    Account FTSActivityAccount;  
   String POVId = System.currentPageReference().getParameters().get('ID');
   boolean errorchecker = false;
            
   public Account getFTSActivityAccount() {
     if(FTSActivityAccount==null){
        try{
        FTSActivityAccount = [Select a.AccountNumber, a.CMA_Verified__c, a.CMACustomerName__c, 
        a.CorpCity__c, a.CorpCountry__c, a.CorpPostalCode__c, a.CorpState__c, 
        a.CorpStreet1__c, a.Name, a.SiteNumber__c 
        from Account a 
        where id=:getEvent().AccountId];
        }catch(Exception e){
        if(masterevent!=null){
            apexPages.message msg = new apexpages.message(apexpages.severity.ERROR,'Account not available for this event');
            ApexPages.addMessage(msg);
        }
        }
    }
    return FTSActivityAccount;
    }

       public Event getEvent() {
        if(masterevent==null){
        try{
        masterevent =[Select e.Subject, e.accountid, e.Sales_Region_FTS__c, e.Products_FTS__c, e.Id, e.Geography_FTS__c, 
        e.Event_Notes_FTS__c, e.Activity_Type_FTS__c, e.ActivityDateTime 
        from Event e 
        where id = :POVId]; 
        }catch(queryexception qe){
        if(errorchecker!=true){
        apexpages.message msg = new apexpages.message(apexpages.severity.INFO,'This Event has been deleted from the system',qe.getmessage());
        apexpages.addmessage(msg);
        errorchecker=true;
        }
        }
        }
        return masterevent;
        }

    
         
    public User[] getFTSInvitee() {
        Set<ID> EVAId = new Set<Id>();
        for(eventattendee gid:[select attendeeid from eventattendee where eventid =:POVId]){
            EVAId.add(gid.attendeeid);
        }
        system.debug('\n\nFound this record to have '+EVAid.size()+' attendees');
        List<User> invitees = new List<User>();
        if(invitees.size()==0){
        invitees = [SELECT Id, Name, Title, Phone, UserRole.Name FROM User where id IN :EVAId];
        }
        if(invitees.size()<1&&FTSActivityAccount!=null){
            ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.INFO,'No Invitees were included on this event');
            apexpages.addmessage(msg);
        }
        return invitees;
        
    } 
    
    public String getSearchText(){
        return null;              
        }
   private List<Account> result = new List<Account>();
   private String searchText;

   public List<Account> getResult() {return result;}
   public void setSearchText(String searchText){
       this.searchText = searchText;
   }
   public pagereference search(){
       System.debug('\n\nThis is the SearchText:'+searchText);
       searchText = '%'+searchText+'%';
       System.debug('\n\nThis is the Final SearchText:'+searchText);
       if(searchText.length()>=3){
           try{
           result = [select a.AccountNumber, a.CMA_Verified__c, a.CMACustomerName__c, 
            a.CorpCity__c, a.CorpCountry__c, a.CorpPostalCode__c, a.CorpState__c, 
            a.CorpStreet1__c, a.Name, a.SiteNumber__c 
            from Account a  Where a.CMA_Verified__C=true and a.Name like :searchText ];
           System.debug(result);
           }catch(queryexception qe){
               apexpages.addmessages(qe);
           }
       }else{
           system.debug('\n\nSearch String too short');
           apexpages.message msg = new apexpages.message(apexpages.severity.INFO,'Search string must be at least 3 characters long');
           apexpages.addmessage(msg);
       }
       return null;
    }
}

 
jwetzlerjwetzler
What browser are you using?  There's a bug in IE (maybe it's a feature to them, I'm not sure) that if you only have one input in a form the enter key does not submit.  That doesn't really explain the refresh but can you just put an empty inputHidden under your current inputText and see if that fixes it?


Message Edited by jwetzler on 08-27-2008 01:57 PM
JimRaeJimRae
Jill,
I am testing with Firefox 3.0.1, but plan to deploy to support IE and Firefox.
I added the inputhidden  as you suggested, but it still has the same results.
Let me know if you think of anything else.
jwetzlerjwetzler
does your action method get called?
JimRaeJimRae
Not on the Enter, but it does when I click the button
JimRaeJimRae

Jill (or anyone),

Any other ideas on this?

I have been working with creating a javascript function that fires onkeypress that checks for the enter keycode ("13") then fires the click() function of my button, but it still seems to rerender the entire page and takes me to a different tab, wiping out my results.

Any help would be greatly appreciated. I know there must be a way to do this!

 

Jim

DavserDavser

I am having a very similar issue.

In my case I start with a page with a single search button. So the first time I hit return, the search perfoms correctly and displays a new section of the page with some additional buttons. if the person then changes the search and hits return, one of these other additional buttons seemingly has gotten focus, and takes control of the "return" press event!

I have tried many things, like putting javascript in to capture a return event on the text input box, however the submit on the button that gets focus seems to take precedence, and forces out my event.

The question is, what is forcing these secondary buttons to get focus? Is it javascript in the page, or browser default behaviour??

DavserDavser

OK, so I figured out the issue that I was having.

My Search button had it's rerender tag set. This means that the button is actually output in HTML with the attribute type="button"

My secondary buttons that appeared after the search had now rerender tag set, which means that this button is output in HTML with the attribute type="submit"

When I hit return for the second time, the browser was assuming that I was submitting the form, and automatically choosing the first submit button it could find and acting like it had been clicked.

By putting in a rerender attribute on these secondary buttons, and having a javascript function listening for a return keystroke I am now able to search multiple times by clicking return.

Hope this helps someone, although I'm not sure it will help the original problem in this thread.

JimRaeJimRae
Davser,
What does your javascript enter key listener look like?  Maybe I have mine coded wrong.

Jim
DavserDavser

The javascript looks like:

Code:
function doSearchOnEnter(e){
 var keynum = 0;
 if (window.event) {
  keynum = window.event.keyCode;
 }else if(e.which){
  keynum = e.which;
 }

 if (keynum == 13) {
  var button = document.getElementById("{!$Component.searchForm.customerChoice.searchButton}");
  button.click();
 }
}

and on my input text field I have an onkeyup event handler:

Code:
<apex:inputText value="{!CustomerSearch}" id="customerSearchInput" onkeyup="doSearchOnEnter(event);"/>


 Which is fairly standard code. With your tabs, I would have a look at the HTML that is output to the browser and search that HTML for a input element of type submit. It could be that there is a submit input element on one of the tabs which is hidden via CSS, but is still picking up the user hitting the return button and causing a complete form submit to happen, which would probably give the behaviour that you are experiencing.
 

TehNrdTehNrd
JimRae,

Where you able to get this working? I have basically copied the javascript that Davser posted but as soon as I hit Enter key the cancel button button is getting executed, not the search.

Code:
<apex:page tabStyle="Lead" controller="resellerSearchVF" id="page">
        <apex:form id="form">
        <apex:pageblock id="pageBlock"> 
            <apex:pageBlockButtons >
             <apex:commandButton value="Cancel" action="{!cancel}"/>
             <apex:commandButton value="Approve" action="{!approve}"/>
                <apex:commandButton value="Reject" action="{!reject}"/> 
            </apex:pageBlockButtons>
            <apex:pageblockSection title="Registration Information" collapsible="false" columns="1">
                <apex:outputField value="{!l.Company}"/>
                <apex:outputField value="{!l.Reseller_Company_Name__c}"/>
            </apex:pageblockSection>
        
            <apex:pageblockSection title="Reseller Search" collapsible="false" columns="1" id="search">
                <apex:outputPanel id="searchfields">
                    <apex:inputText value="{!searchValue}" id="searchtext" onkeyup="doSearchOnEnter(event);"/>
                    <apex:commandButton value="Search" action="{!searchAccounts}" rerender="results,error" status="search" id="searchButton"/>

<script type="text/javascript">
          
    function doSearchOnEnter(e){
       alert(e);
       var keynum = 0;
       if (window.event) {
          keynum = window.event.keyCode;
       }else if(e.which){
          keynum = e.which;
       }
 
       alert('keynum: ' + keynum);
 
       if (keynum == 13) {
          button = document.getElementById("{!$Component.page:form:pageBlock:search:searchButton}");
          button.click();
       }
    }
    </script>


Controller:

public PageReference cancel(){
PageReference cancel = new PageReference('/' + ApexPages.currentPage().getParameters().get('id'));
cancel.setRedirect(true);
return cancel;
}

 

JimRaeJimRae
I was not able to get it working directly. Ultimately, I redesigned my page in a way that had the search inputtext item be the first input item that gets rendered, then it seemed to work OK.
TehNrdTehNrd
Did you just place the inputText field first on the page or did you hide the buttons upon initial load and then with a javascript onLoad rerender the buttons?
JimRaeJimRae
I put the inputtext on the first page (actually the first tab of a multi-tab view).
TehNrdTehNrd
Hmm, ok. Not really an option with my design.

I even removed all of the fields so that only a inputText and commandButton remain. If I type and hit enter it refreshes the entire page rather then just performing the rerender.

Thanks for the help but I'm done burning cycles on this one. The users will just have to learn to click the search button rather than hit enter.
JohanLiljegrenJohanLiljegren
Hey TehNrd and JimRae,

Does it make a difference if you have only one Search button on the page or does that refresh the entire page when hitting Enter as well?
I got my page working yesterday, but I only have one button.
If you think that could help I'll post a simplified version of my page here.

Regards
//Johan Liljegren
JimRaeJimRae
Yes, the issue is if you have multiple buttons on the page.  In my scenario, I had a multi-tabbed page, similar to the tabbed account page example code, the search page was on the 4th tab, but when I would hit enter (with the javascript in place) the page would refresh and take the user back to the first tab, and wipe out the search results in the process.
I ended up moving the search function to the first tab to get it to work.
Greg RohmanGreg Rohman

Hi Johan.

 

I'm having the same Enter key problem, but only have a single text input and a single button on the page. I've tried adding the hidden field, and have also tried the Javascript solution, but cannot get either working. Could you post your simplified code?

 

Thanks in advance.

 

-Greg 

Rajesh ShahRajesh Shah

Found an interesting thing:

 

When the commandButton has reRender attribute associated with it, it is rendered with type="button" in html. Else it is rendered as type="submit". With submit, the enter key works fine; not with button.

 

Now if I have to make my enter key work, I have to remove rerender. This reloads the whole page and since my page has got images, the reload takes time and doesn't looks good. I need the reRender and also have to use the enter key. I tried by capturing the enter key event and clicking the button using Javascript. It executes the Action method but doesn't rerenders anything. 

 

Is there any solution for this?

This was selected as the best answer
JohannesBorrmanJohannesBorrman
what exactly do you have to rerender on your page?
Rajesh ShahRajesh Shah
I was trying to rerender a pageBlockTable.
JohannesBorrmanJohannesBorrman
rerendering tables is tricky but i found out a nearly 100% and everytime working way ... but this is offtopic as it was about the enter key wasn't it?
Rajesh ShahRajesh Shah
yes ... and i have still not found any solution for it.  :smileysad:
JohannesBorrmanJohannesBorrman

for what - getting the enter key hit? i made a inputtext field working on enter hit instead of pushing a button. 

<script type="text/javascript"> window.captureEvents(Event.KEYPRESS); window.onkeypress = Ausgabe; function Ausgabe(Ereignis) { if(Ereignis.which == 13){ SonE(); } } </script> <apex:actionFunction action="{!ViewData}" name="SonE"></apex:actionFunction>

the javascript looks for enter key and starts an action function ... (which does the same as the button - doing a pagereference action. tried that already? 

 

 

calimuchocalimucho

Hi all,

 

For me the code works perfect. In my VisualForce page, I have 3 commandButtons.

But just one have to rerender the pageBlock. I do some research on the web.

And it appears that a commandButton with a rerender has the type="Button"

and a commandButton with no rerender has the type="Submit".

So if you want that the code work, you need to specify the rerender on all you 're commandButtons.

 

P.S. : I change a little bit the code to not use a lot of javascript function. Here is an example of my code :

 

<apex:form id="formId"> <script type="text/javascript"> function handleKeyPressSearch(event){ if (event.which == 13){ actionSearchScript(); } } </script>

<apex:actionFunction action="{!actionSearch}" name="actionSearchScript" />
<apex:pageMessages id="errorMessages"/>

 <!--

...

-->

<apex:inputText value="{!searchStr}" id="idSearch" onkeypress="handleKeyPressSearch(event);"/> <apex:commandButton action="{!actionSearch}" value="{!$Label.searchButton}" reRender="PgBTableListId, errorMessages" id="commandButtonSearchId"/> <!-- ... --> </apex:form>

 I skip the page presentation for more visibilty.


 

 

calimuchocalimucho

Sorry, I write too quickly. It's not working on IE 7.

Any ideas why?

JohannesBorrmanJohannesBorrman

<script type="text/javascript"> function catchEnterKey(eVnt) { if (!eVnt) eVnt = window.event; doSrch(); } document.onkeyup = catchEnterKey; </script>

 

 

This should do it - had no IE7 though but recognized it didn't work with IE6 too.

calimuchocalimucho

I found how correct the problem. Here is my code

 

 

<script type="text/javascript"> function handleKeyPressSearch(event){ var keyCode; if (event && event.which){ // Use for Firefox and Chrome keyCode = event.which; } else { // Use for IE keyCode = event.keyCode; } if (keyCode == 13){ actionSearchScript(); } } </script>

 

 

 

rbkrbkrbkrbk

To avoid the Enter keypress from having other effects (like re-rendering the entire page),

I found I had to clear the keyCode before returning

Thusly:

 

if (keyCode == 13){ actionSearchScript(); event.keyCode = null; }

 

 

 

JasonMeketaJasonMeketa

Combining everything people have said worked for me in all major browsers. Here it is. 

 

<script type= "text/javascript">

 

function handleKeyPressSearch(event){

 

var keyCode;

 

if (event && event.which){

 

// Use for Firefox and Chrome

 

keyCode = event.which;

 

} else {

 

// Use for IE

 

keyCode = event.keyCode;

 

}

 

if (keyCode == 13){

 

actionSearchScript();

 

event.keyCode = null;

 

}

 

}

 

</script>

 

apex:actionFunction action="{!queryCases}" name="actionSearchScript" />apex:inputText value="{!searchParam}" id="idSearch" onkeypress="handleKeyPressSearch(event);"/>

 

 

 

 

 

 

 

<

<

TankGirlTankGirl

I am having a similar issue, but my isn't in a 'tabbed' view and I am using a commandLink instead of a button. I tried the above suggestions and even a jQuery version:

 

$('#input_text').keyup(function(e) {
	//alert(e.keyCode);
	if(e.keyCode == 13) {
		alert('Enter key was pressed.');
	}
});

 But it still refreshes the page and puts '?core.apexpages.devmode.url=1' in the URL.... I have tried removing the reRender and changing the link to a button, but still nothing seems to work.

 

 

Here is my code:

 

<apex:inputtext id="searchField" value="{!searchText}" styleclass="cInput floatL"/>

<apex:commandLink value="Search" styleClass="cLabel cSearchBtn" id="searchButton" onClick="loaderIcon(true);" action="{!searchKB}" reRender="resultsWrap" oncomplete="loaderIcon(false);"> <apex:actionSupport event="onclick" rerender="resultsWrap" /> </apex:commandLink>

 Help would be appreciated!

 

AidenAiden

Setting 

 

event.keyCode = null;

 

gave me an issue in Firefox. Firebug reported that only a getter is supported for this property. In my case, I changed this to;

 

event.preventDefault(); 

TankGirlTankGirl

So i got it to work with a regular <apex:commandButton &  <apex:inputTex:

 

 

<apex:inputtext id="searchField" value="{!searchText}" styleclass="cWatchInput" />

<apex:commandButton value="{!$Label.Search}" styleClass="cSearchBtn" id="searchButton" onClick="loaderIcon(true);" action="{!searchKB}" reRender="resultsWrap" oncomplete="loaderIcon(false);"> 

 

And then some jQuery to make it all go

 

jQuery.noConflict(); // so there is no conflicts with salesforce code

jQuery(document).ready(function(){ //Wait for the page to load

jQuery('.cWatchInput').keypress(function(e) { //every time a key is pressed
code = e.keyCode ? e.keyCode : e.which; //multi browser support
if (code.toString() == 13){ // enter key is code 13
e.preventDefault(); //very important!! this prevents the normal action
if(jQuery('.cWatchInput').val().length >= 3){ //checks for at least 3 char in the field
jQuery('.cSearchBtn').click(); // clicks the button and starts the action } } }); });

 

 

Razi Haider 5Razi Haider 5
If you need development in yourself and you live in India then go for Indian Scheme Site https://www.sarkariguruji.com/