[SalesForce] Jquery document.ready function is not working after calling apex method

I have jquery document ready issue. I wrote the below code and document.ready function is working until the apex method is called. Once apex method is called, the event is not firing.
I need some help.

<script type="text/javascript">
    var j$ = jQuery.noConflict();

    j$(document).ready(function(){
        j$("#table").change(function () {
            calcTotal();
        });       
    });

    function getPrice(){
        calc();
    }

    function calcTotal(){
      /// sum each value //
    }
</script>

<apex:form id="form">
    <apex:pageMessages id="msg" escape="false"/>
    <apex:actionFunction name="calc" action="{!getPrice}" reRender="block" oncomplete="calcTotal();"/>
    <apex:pageBlock id="block">
        <table id="table">
            <apex:repeat value="{!sampleList}" var="s">
                <tr>
                    <apex:inputField value="{!s.Sample__r.Account_c}" onchange="getPrice();">
                    <apex:inputField value="{!s.Price1__c}"/>
                    <apex:inputField value="{!s.Price2__c}"/>
                    <apex:inputField value="{!s.Price3__c}"/>
                    <apex:inputField value="{!s.Price4__c}"/>

                    //more input Field//
                    <apex:outputText value="{!s.Total__c}"">
                </tr>
            </apex:repeat>
        </table>
    </apex:pageBlock>
<apex:form>

Best Answer

The general pattern to use here is to re-run the jQuery logic once the re-render is complete:

<script type="text/javascript">

function addChangeListener() {
    var j$ = jQuery.noConflict();

    j$(document).ready(function(){
        j$("#table").change(function () {
            calcTotal();
        });       
    });

    function getPrice(){
        calc();
    }

    function calcTotal(){
      /// sum each value //
    }
}

// Run when page first loads
addChangeListener();

</script>

<!-- Run when re-render is complete -->
... reRender="block" oncomplete="addChangeListener();"/>

The jQuery ready will execute immediately in the re-render case so adding the change handler.

Related Topic