ylnsagar
ylnsagar

Reputation: 644

set focus to next input element after jsf's change value listener

in one of our front-end screens we have the following layout as follows

<h:outputLabel for="firstName" value="first name" />

<h:inputText styleClass="required" id="firstName"  size="30"  maxlength="30" 
        value="#{ownershipStoreInfoController.form.ownerFirstName}" onchange="submit()"
        valueChangeListener="#{ownershipStoreInfoController.useOwnerInfo}">
        <e:validateRegExpr pattern="([A-Z,a-z,0-9,%@()#&amp;,.;:_\$\/\-\{\}\[\]\'\\s*]{1,30})?" />
</h:inputText>


<h:outputLabel for="lastName" value="last name" />

<h:inputText styleClass="required" size="30" id="lastName" maxlength="30"
                    value="#ownershipStoreInfoController.form.ownerLastName}"
                    onchange="submit()"
                    valueChangeListener="#{ownershipStoreInfoController.useOwnerInfo}">
                    <e:validateRegExpr pattern="([A-Z,a-z,0-9,%@()#&amp;,.;:_\$\/\-\{\}\[\]\'\\s*]{1,30})?" />
</h:inputText>

when i enter value in the input field "firsName" and enter "Tab", the change listener gets called and everything looks fine.

but the problem is since its making server call and coming back to the screen. the focus of the cursor to the next input box("lastName") is not working and focus disappears on firstname field too. the only way its working is me to place my mouse manually in the next field.

i need the focus to get on to the field("lastName"). after i change a value in "firstName" and click tab button.

any help is appreciated.

Upvotes: 0

Views: 1399

Answers (1)

ylnsagar
ylnsagar

Reputation: 644

finally i found the solution. in my Value Change Listener. i added this statement at the end.

if(event.getComponent().getId().equalsIgnoreCase("COMPONENT ID FIRST")){
        String jsStatement = "document.getElementById(\'" + ("COMPONENT ID SECOND")+ "\').focus();";
        SESSIONCLASS.setBodyOnload(jsStatement);        
    }

in the above code "COMPONENT ID FIRST" is the current component where your value change listener is triggered and "COMPONENT ID SECOND" is the next component where your focus has to be set.

SESSIONCLASS is class which is available in session and "setbodyonload" is a string which accepts string as a parameter. make sure you have getter and setter methods as follows in SESSIONCLASS

public String getBodyOnload() {
    return bodyOnload;
}

public void setBodyOnload(String bodyOnload) {
    this.bodyOnload = bodyOnload;
}

and finally i put a scriplet in my JSP page as follows.

<%
    String bodyAttributes = "";
    String onload = SESSIONCLASS.getBodyOnload();
    if (onload != null) 
    {
        bodyAttributes = " onload=\""+onload+"\"";
        SESSIONCLASS.setBodyOnload(null); // clear bodyOnload
    }
%>

so here when the page loads after change value listener. the scriplet executes lets the focus to be on desired component.

Upvotes: 1

Related Questions