Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

jsf - Process onclick function after ajax call <f:ajax>

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)

  • add onevent="myFunc();" to f:ajax => leads to refreshing page
  • add onevent="myFunc()" to f:ajax => same behaviour as onclick attribute
  • next f:ajax with onevent attr. => still the same

update2 (how it should works):

  • submit button is ajax called
  • form is cleaned as needed
  • appropriate field is focused (depended on some user choosed factors)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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" />

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...