Question

My code is working fine, but I am really not able to clearly understand it.

Can someone explain me please.

This is my code:

<script type="text/javascript">
    var portletNamespace = '#<portlet:namespace/>\\:formId\\:';
    $(portletNamespace + 'drpCategory').live('change', function () {
        alert('#{myController.simpleString}');
        $(portletNamespace + 'hiddenValue').ready(function () {
            alert($(portletNamespace + 'hiddenValue').val());
        });
    });
</script>

<h:inputText id="hiddenValue" value="#{myController.simpleString}" />

<h:selectOneMenu id="drpCategory">
    <f:selectItem itemLabel="Chọn thủ tục" itemValue="#{null}" />
    <f:selectItems value="#{myController.listCate}" var="item" itemLabel="#{item.cateNane}"
    itemValue="#{item.cateId}" />
    <f:ajax event="valueChange" render="hiddenMap " listener="#{myController.changeCategory}"
    />
</h:selectOneMenu>

after I change item in drpCategory, javascript alerts empty string first and then real value of simpleString. But if I remove the first alert code, the second will show me old value (before rendered by ajax)

For example, if I remove first alert code. First, hiddenValue is empty, change drpCategory value, hiddenValue changed to 'a' but javascript alert empty, second time when I change drpCategory then hiddenValue is changed to 'b' but it will still show 'a'.

edit: ah, I find out something, I had changed to:

 <script type="text/javascript">
    var portletNamespace = '#<portlet:namespace/>\\:formId\\:';     
    $(portletNamespace+'drpCategory').live('change', function(){
        setTimeout('myFunc()', 500);    

    });

    function myFunc(){
            $(portletNamespace+'hiddenValue').ready(function(){
                alert($(portletNamespace+'hiddenValue').val());
            });
    }
   </script> 
Was it helpful?

Solution

If I understood your scenario right..

Change your

<f:ajax event="valueChange" render="hiddenMap " listener="#{myController.changeCategory}"
/>

into

<f:ajax onevent="callThisMethodAfterValueIsUpdated" event="valueChange" render="hiddenMap " listener="#{myController.changeCategory}"
/>

and in your js add this

var portletNamespace = '#<portlet:namespace/>\\:formId\\:'; 
function callThisMethodAfterValueIsUpdated(data) {
    if (data.status === 'success') {
        alert($(portletNamespace+'hiddenValue').val());
    }
}

relying on setTimeout is wrong cause it may vary from time to time server/traffic...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top