Wednesday, February 22, 2012

SharePoint 2010 : Using ECMA script recall javascript function on control click in UpdatePanel.

I dont know if this is important or not but I found this thing interesting to blog.

Goal

There is a in UpdatePanel on the page. We have to call a javascript everytime the page is postback. Even if it is a postback from a control under UpdatePanel. I discovered a way using ECMA using which we can easily call the javascript function.

Solution

<script>!window.jQuery && document.write('<script src="http://code.jquery.com/jquery-1.4.2.min.js"><\/script>');</script>
<script type="text/javascript">
    //Call the function or assign the event on ready
    $(document).ready(function(){
        //This will wait until script is loaded and than call our function
        ExecuteOrDelayUntilScriptLoaded(PageLoadEvent, "sp.js");
    });
    
    //This function is the most important function that will add the end request
    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(FunctionHandler);
    
    //Event handler that fires on the UpdatePanel control events too
    function FunctionHandler(sender, args) {
        ExecuteOrDelayUntilScriptLoaded(ButtonClickEvent, "sp.js");
    }
    
    //Write the time on page load
    function PageLoadEvent(){
        alert('Page Load : ' + (new Date()).toString() );
    }

    //Will call on button click event
    function ButtonClickEvent(){
        alert('Button Click : ' + (new Date()).toString() );
    }                
</script>
<asp:UpdatePanel ID="upPanel" runat="server">
    <ContentTemplate>
        <asp:Button ID="btn" runat="server" Text="Click here!!!" />
    </ContentTemplate>
</asp:UpdatePanel>


Important Note

The most important thing in this is, if you remove "Sys.WebForms.PageRequestManager.getInstance().add_endRequest(FunctionHandler);" and try clicking the button the event wont be raised to call "function ButtonClickEvent()". So that is the magic trick.

Let me know if this helped you!

No comments:

Post a Comment