I'm trying to select and focus to choosed component ID after submit a form (ajax call).
<script>
var myFunc = function() {
document.getElementById('form:#{bean.componentId}').focus();
document.getElementById('form:#{bean.componentId}').select();
};
$(document).ready(function() {
myFunc();
});
</script>
<h:form id="form">
<h:commandButton action="#{bean.save}" onclick="return myFunc();" ...>
<f:ajax execute="@form" render="@form"/>
</h:commandButton>
...
</h:form>
This solution is working, but problem is, that <f:ajax>
is called AFTER onclick
, so the the form is rendered after component selection, and focus is cleared.
How can I call my function AFTER the form is rendered?
update: (I've tried for example)
onevent="myFunc();"
to f:ajax
=> leads to refreshing pageonevent="myFunc()"
to f:ajax
=> same behaviour as onclick
attributef:ajax
with onevent
attr. => still the sameupdate2 (how it should works):
If you use AJAX on your website, beware that events like click, submit, hover might not work if you don't attach them properly. I will be using click event to describe the problem, but all of this applies to most events in jQuery.
The ajax() method in jQuery is used to perform an AJAX request or asynchronous HTTP request. Parameters: The list of possible values are given below: type: It is used to specify the type of request. url: It is used to specify the URL to send the request to.
The onevent
handler will actually be invoked three times and it should point to a function name, not the function itself. One time before the ajax request is been sent, one time after the ajax response is been arrived and one time when the HTML DOM is successfully updated. You should be checking the status
property of the given data argument for that.
function listener(data) {
var status = data.status; // Can be "begin", "complete" or "success".
switch (status) {
case "begin": // Before the ajax request is sent.
// ...
break;
case "complete": // After the ajax response is arrived.
// ...
break;
case "success": // After update of HTML DOM based on ajax response..
// ...
break;
}
}
In your particular case, you thus just need to add a check if the status is success
.
function myFunc(data) {
if (data.status == "success") {
var element = document.getElementById('form:#{bean.componentId}');
element.focus();
element.select();
}
}
And you need to reference the function by its name:
<f:ajax ... onevent="myFunc" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With