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
Logan Smith 10Logan Smith 10 

Why can't I get focus to stay on input field using javascript or apex:actionFunction

I have a page that I use to search Entries in a Journal in our Salesforce Communities visualforce page. The system works just fine, except that I have been asked to make it search upon keyup. This was obviously easy, but presented a problem that I can't seem to figure out! If you type the text quickly, you can type whatever you want, but if there is even the slightest pause, the search happens and focus is lost from the input field. I kinda expected focus to be lost, but what I didn't anticipate, was not being able to use JS or apex:actionFunction to regain focus. I have tried JS to give focus upon load of the page, but it wont, I have tried creating a simple button that gives focus to the inputfield, but it wont. If you click on the input field, it will hold focus until the action is performed, but otherwise, it will not "take focus". Would you please look at my code and tell me where I'm going wrong?
The visualforce page:
<apex:page showHeader="false" standardStylesheets="false" controller="SOSLController" cache="false" action="{!soslLoad_method}" docType="html-5.0" applyHtmlTag="false">
<head>
<meta charset="utf-8"/>
<title>My Journal</title>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<meta name="generator" content="Webflow"/>
<link href="{!URLFOR($Resource.Webflow_CSS, 'css/normalize.css')}" rel="stylesheet"/>
<link href="{!URLFOR($Resource.Webflow_CSS, 'css/webflow.css')}" rel="stylesheet"/>
<link href="{!URLFOR($Resource.Webflow_CSS, 'css/eyes2cNoLinks.css')}" rel="stylesheet"/>


<script type="text/javascript" src="{!URLFOR($Resource.Webflow_JS, 'js/modernizr.js')}"></script>
<link rel="shortcut icon" type="image/x-icon" href="https://s3.amazonaws.com/eyes2c/Images/favicon-32x32.png"/>
<link rel="apple-touch-icon" href="https://s3.amazonaws.com/eyes2c/Images/Eyes2CLogo.png"/>

<script src="https://ajax.googleapis.com/ajax/libs/webfont/1.4.7/webfont.js"></script>
<script>
WebFont.load({
    google: {
      families: ["Droid Serif:400,700","Roboto:300,regular,500","Roboto Slab:regular"]
    }
  });
</script>

</head>



<!--This is what I use to toggle through detailed and simple version of Table--> 
<script type="text/javascript">
function hideshow(which){
if (!document.getElementById)
return
if (which.style.display=="none")
which.style.display="block"
else
which.style.display="none"
}
</script>


<body  id="TheTop" class="BG">

<apex:form >

<!--The focus part of this does not work-->

<apex:actionFunction name="saveUpdates" focus="myAnchor" action="{!soslDemo_method}"/>

<script>
saveUpdates();
</script> 

<script>
function getfocus() {
document.getElementById("myAnchor").focus();
}
</script>

<!--I made this button to test the function, and it does not work-->

<input type="button" onclick="getfocus()" value="Get focus"/>


<!--This is the input field that loses focus-->

  <apex:inputText id="myAnchor" tabindex="1" styleClass="inputField"  onkeyup="saveUpdates()" value="{!searchStr}" />


<!--I have two of these for toggling between 
detailed and simple versions of table-->

<div id="but1" style="display: block" class="ck-button" onclick="javascript:hideshow(document.getElementById('but1')); javascript:hideshow(document.getElementById('but2')); javascript:hideshow(document.getElementById('adiv1')); javascript:hideshow(document.getElementById('adiv2'))"><label><input style="display: none" type="checkbox" value="1" onclick="javascript:hideshow(document.getElementById('but1')); javascript:hideshow(document.getElementById('but2')); javascript:hideshow(document.getElementById('adiv1')); javascript:hideshow(document.getElementById('adiv2'))">Browse</input></label>    </div>

<apex:actionStatus id="actStatusId">
            <apex:facet name="start" >
                <img src="/img/loading.gif"/>                    
            </apex:facet>
</apex:actionStatus>
</apex:form>

 <apex:outputPanel title="" id="error">
 <apex:pageMessages ></apex:pageMessages>
 </apex:outputPanel>

<div id="adiv1" style="display: block">
<apex:repeat value="{!entlist}" id="entr" var="ent" rendered="true">

<!--All of my table data Simple View-->

</apex:repeat>
</div>


<div id="adiv2" style="display: none">
<apex:repeat value="{!entlist}" id="entr1" var="ent" rendered="true">

<!--All of my table data for Detailed View-->

</apex:repeat>
</div>




<footer>


<script type="text/javascript">
function addLoadEvent(func) { 
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            oldonload();
            func();
        }
    }
}

function setFocus() {
    document.getElementById('{!$Component.myAnchor}').focus();
}
addLoadEvent(setFocus);
</script>
</footer>


</body>
</apex:page>

My Controller:
 
Public with sharing class SOSLController{
Public List<Journal_Entry__c> entList {get;set;}

Public String searchStr{get;set;}

Public void SOSLController(){
}
Public void soslLoad_method(){

        List<List <sObject>> searchList = [FIND 'All' IN ALL FIELDS RETURNING 
                                           Journal_Entry__c (Id,Name,Color__c,ShowTrueFalse__c,ShowTrueFalse2__c,Context__c,Entry_Series__c,SelfID__c,Related_to_Previous_Dream__c,Scene_One__c,Scene_Two__c,Self_Interp__c,CreatedDate,DateText__c,Submitted_for_Interp_Count__c,Classification__c,Created_Self_Interp__c,Haven__c,UserID__c 
                                                             WHERE UserID__c = :UserInfo.getUserId() ORDER BY CreatedDate Desc)];
            entList = ((List<Journal_Entry__c>)searchList[0]);

}

Public void soslDemo_method(){


    if(searchStr.length() < 2)
    {
        List<List <sObject>> searchList = [FIND 'All' IN ALL FIELDS RETURNING 
                                           Journal_Entry__c (Id,Name,Color__c,ShowTrueFalse__c,ShowTrueFalse2__c,Context__c,Entry_Series__c,SelfID__c,Related_to_Previous_Dream__c,Scene_One__c,Scene_Two__c,Self_Interp__c,CreatedDate,DateText__c,Submitted_for_Interp_Count__c,Classification__c,Created_Self_Interp__c,Haven__c,UserID__c 
                                                             WHERE UserID__c = :UserInfo.getUserId() ORDER BY CreatedDate Desc)];
            entList = ((List<Journal_Entry__c>)searchList[0]);

    } else {
        String searchStr1 = '*'+searchStr+'*';
        List<List <sObject>> searchList = [FIND :searchStr1 IN ALL FIELDS RETURNING 
                                           Journal_Entry__c (Id,Name,Color__c,ShowTrueFalse__c,ShowTrueFalse2__c,Context__c,Entry_Series__c,SelfID__c,Related_to_Previous_Dream__c,Scene_One__c,Scene_Two__c,Self_Interp__c,CreatedDate,DateText__c,Submitted_for_Interp_Count__c,Classification__c,Created_Self_Interp__c,Haven__c,UserID__c 
                                                             WHERE UserID__c = :UserInfo.getUserId() ORDER BY CreatedDate Desc)];
        entList = ((List<Journal_Entry__c>)searchList[0]);
        if(entList.size() == 0){
            apexPages.addmessage(new apexpages.message(apexpages.severity.Error, 'Sory, no results returned with matching string..'));
        }
    }            
}
}

I suspect that the problem with all of this has something to do with the rerendering after each onkeyup, but that wouldn't explain why other functions such as on page load and apex:actionFunction don't work...
I would greatly appreciate any insight!
Best Answer chosen by Logan Smith 10
Logan Smith 10Logan Smith 10
OK, someone told me the answer on salesforce.stackexchange (http://salesforce.stackexchange.com/questions/117151/why-cant-i-get-focus-to-stay-on-input-field-using-javascript-or-apexactionfunc):  "Using an apex input field means the ID will actually be different than that in the DOM. What happens if you switch your selector to document.getElementsByClassName("inputField")[0].focus() – cricketlang"  By changing the getElements to ClassName rather than the Id, I was able to get focus of the apex input box.  Also, I used 
onfocus="this.value = this.value;"
to place the cursor at the end of the text each rerender.

This was a problem that I could find no help on throughout dozens of forums, so I hope that it is helpful to someone else out there!