1
votes

I'm trying to implement select (and focus) the component based on validation decision.

For example:

  • login form (2 inputs: username, password; 1 submit button)
  • if the validation fail on username, <h:inputText id="name"> will be focused
  • if the validation fail on password, <h:inputSecret id="password"> will be focused
  • page will not be refreshed, submit is an ajax button

What I've tried:

without ajax call (this is working fine - componentId is set in bean in validation proccess, and selected/focused after each page refresh/submit):

$(document).ready(function() {
  document.getElementById('form:#{bean.componentId}').focus();
  document.getElementById('form:#{bean.componentId}').select();
});
...
<h:commandButton id="save" action="#{bean.save}" type="submit"/>

BUT with ajax call:

function myFunc(data) {
  if (data.status == "success") {
    var element = document.getElementById('form:#{bean.componentId}');
    element.focus();
    element.select();
}}
...
<h:commandButton id="save" action="#{bean.save}" type="submit">
  <f:ajax execute="@form" render="@form" onevent="myFunc"/>
</h:commandButton>

This way is also working, problem is, componentId is still the same (the one, which is inicialized during bean creation).

Previous questions related to this topic:

How can I use ajax submit button and select/focus to the field with validation error???

1

1 Answers

3
votes

The non-ajax submit re-renders basically the entire page, including the scripts. The ajax submit re-renders only a part of the page, which is in your particular case only the form itself (as controlled by <f:ajax render> attribute). The scripts are apparently not placed in the form and hence they keep the "old" values (you know, EL #{} runs in webserver and doesn't run in webbrowser, so at the moment the webbrowser retrieves the HTML/JS code, EL has already run for long, it won't be re-executed when you call the JS code).

You need to put the script block with those EL expressions in the same form as well, so that it will also be updated on ajax submit.