How to set the focus of the inputText inside dataTable

Good Afternoon,

Using JSF + Primefaces. I have a dataTable with inputText field, which performs a listner, and when you end the function or pressing tab, the focus would be to input the low line of the same component.

Googled some things, and it seems that's to be done with JavaScript or jQuery, but I have not much knowledge.

It seems that the clientId of the component has something form: dataTable: 0: input, and the number "0" to manipulate the focus. Anyone know how to work the focus of components within the dataTable?

Thank you.


Add proper and dynamic ids for your components then you can identify your elements quite easily.

Consider following code snippet:

<ice:form id="form1"/>
    <ice:dataTable id="dataTable1">
        ...
        <ice:inputText id="inputText1"  />
        <ice:commandButton id="commandButton1" value="Set Focus" onclick="javascript: setFocusOfInput(this);" />
        ...
    </ice:dataTable>
</ice:form>

And the javascript part:

function setFocusOfInput(obj){
    var objectId = obj.id;
    var requiredIndex  = objectId.indexOf(':commandButton1');
    var formId = objectId.substring(0, requiredIndex); 

    alert(formId); /* You will get your form id here, no-matter if you don't set. */

    /* Now you can get your required element and do-whatever you want. */
    var inputText1 = document.getElementById(formId +':inputText1');
    inputText1.focus();
}

Just add a proper id for your element to distinguish it from others.


You could use the PrimeFaces element <p:focus /> , and in the "context" attribute, put the ID of the dataTable. The "context" attribute serves to set the root component to start first input search, so if you are using AJAX, you could update the container where the "dataTable" and the "focus" elements are wrapped, and the first input in the dataTable will recieve the focus after AJAX call:

<p:focus context="dataTable" />

You could use the "for" attribute too, if you want to refer the input directly:

<p:focus for="inputText" />

Take a look to the PrimeFaces documentation: p:focus.

链接地址: http://www.djcxy.com/p/76662.html

上一篇: 如何创建自定义Java注释来记录方法参数

下一篇: 如何设置dataTable中inputText的焦点