My goal is to set the focus to a specific inputText.
As there seems to be no way to do this automatically with an tr:inputText property, I try to use Javascript.
For document.getElementById
I need the id of the rendered html <input>
. I try to set this id to the correct index. However, it is rendered with the id varFieldIterator:0:varField
where the number 0 comes from the iterator and is different depending on my start value selectionStart. If I start with selectionStart = 10, the 1st index for the textbox 10 is 0. If I start with 15 and then have a PPR to show the first 15 textboxes, they get the id starting with 16.
I think the code will make clear what I try to achieve:
<tr:iterator
id="varFieldIterator"
value="#{myController.form.model.fieldList}"
var="field"
rows="15"
first="#{{myController.form.model.selectionStart}"
varStatus="status">
<tr:inputText
id="varField#{status.index}"
value="#{field.value}"
label="Text #{status.index +1}">
</tr:iterator>
<tr:inputHidden
id="FOCUS_TEXT"
value="#{myController.form.model.endFocus}"></tr:inputHidden>
<trh:script>
window.onload = function() { document.getElementById('varField' + document.getElementById('FOCUS_TEXT').value).focus(); }
</trh:script>
While the ID attribute accepts EL expressions, it is only set during view build time, not during view render time. So if you were using a view build time tag such as JSTL <c:forEach>
it would have worked. But this tag may have undesireable side effects.
I'd recommend to just change your JavaScript function so that it does not depend on IDs anymore. It's unclear what your entire HTML dom structure is and if you're using jQuery or not which would simplify HTML DOM traversal.
With plain JS, you could for example just grab the first form and then grab its first input element:
document.forms[0].elements[0].focus();
Or you could grab input elements by tag name:
document.getElementsByTagName("input")[0].focus();
Or you could give them all a class name like <tr:inputText styleClass="specificInput">
and grab them by class name:
document.getElementsByClassName("specificInput")[0].focus();
Those calls are chainable. So if you know that it's inside a <h:form id="myForm">
then you could also do for example:
document.getElementById("myForm").getElementsByTagName("input")[0].focus();