Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Primefaces inputtext focus at the end of the text

Here a snippet of my JSF:

<p:tabView id="tabView" var="tab" value="#{data.tabs}" widgetVar="tabViewWidget"
                activeIndex="#{data.newActiveTabIndex}">

                <p:ajax event="tabClose" listener="#{logic.closeTab}" />

                <p:tab title="#{tab.content.title != null ? tab.content.title : '&amp;lt;new&amp;gt;'}"
                    closable="#{tab.isClosable and data.tabs.size() > 2}">
                    <h:outputText value="#{tab.id} Test" />

                    <p:focus rendered="#{data.componentIdToFocus != null}" for="#{data.componentIdToFocus}" />

                    <p:inputText id="test" value="#{tab.content.title}">
                        <p:ajax event="keyup" listener="#{logic.setFocusingComponent}" update=":form:tabView" />
                    </p:inputText>
                </p:tab>

            </p:tabView>

The intent is that there is a textfield within each tab that updates the title of the tab while writing. The given snippet works except that p:focus places the cursor at the beginning of the text that is already written. I want the cursor to be placed at the end of the text already written. So that a user can type and while he/she is typing the title adapts automatically.

I hope my case is clear. Does anybody have a solution for that?

Best regards, Florian

like image 749
Florian Huonder Avatar asked Nov 19 '25 01:11

Florian Huonder


1 Answers

You can use the onfocus="this.value=this.value" trick to "deselect" the value so that the cursor automagically ends up in the end of the value. This should work as good for the <p:inputText> as it basically generates just a <input type="text"> element.

<p:inputText ... onfocus="this.value=this.value" />

See also:

  • Use JavaScript to place cursor at end of text in text input element

Unrelated to the concrete problem, I wouldn't use ajax and such on keyup event and an update of the whole tabview. This seems to be quite expensive. I'd rather do a simple HTML DOM traversion and manipulation here by JS/jQuery.

E.g.

<p:inputText ... onkeyup="updateTitle(this)" />

with

function updateTitle(inputInTab) {
    var panelId = $(inputInTab).closest(".ui-tabs-panel").attr("id");
    $("a[href='#" + panelId + "']").text(inputInTab.value);
}
like image 119
BalusC Avatar answered Nov 22 '25 02:11

BalusC