Updating controls via JQuery from inside an UpdatePanel

Recently we encountered an issue when we were trying (unsuccessfully) to update a link outside an Ajax UpdatePanel using jQuery.
We wrote the change events and we noticed that they only fired once and no more. Clicking on the tickbox proved to be futile. Not even 317 clicks seemed to work.
original

After a bit of research, we found out that the Update Panels only subscribe to the page load event once and afterwards they drop the events, unless you rebind them once more.
To rebind them, you need to call the PageRequestManager and connect to the endRequest method.

var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function () {…});

$('#ctl00_ContentPlaceHolder1_chkLinkedSuppliers').on('change', function () {
        if ($('#ctl00_ContentPlaceHolder1_lnkAuditReport2').length > 0)
        {
            var href = $('#ctl00_ContentPlaceHolder1_lnkAuditReport2').attr("href");
            ///Reports/AuditReport2.aspx?ID=21074&ShowAll=0&ShowAllSystems=0&ShowAllCompanies=0&ShowAllLinked=1
            href = href.replace("&ShowAllLinked=1","").replace("&ShowAllLinked=0","");
            if($(this).is(":checked")) {
                href = href + "&ShowAllLinked=1";
            }else{
                href = href + "&ShowAllLinked=0";
            }

            $('#ctl00_ContentPlaceHolder1_lnkAuditReport2').attr("href", href);
        }

    });

    var prm = Sys.WebForms.PageRequestManager.getInstance();

    prm.add_endRequest(function () {
        // re-bind your jQuery events here

        $('#ctl00_ContentPlaceHolder1_chkLinkedSuppliers').on('change', function () {
            if ($('#ctl00_ContentPlaceHolder1_lnkAuditReport2').length > 0) {
                var href = $('#ctl00_ContentPlaceHolder1_lnkAuditReport2').attr("href");
                ///Reports/AuditReport2.aspx?ID=21074&ShowAll=0&ShowAllSystems=0&ShowAllCompanies=0&ShowAllLinked=1
                href = href.replace("&ShowAllLinked=1", "").replace("&ShowAllLinked=0", "");
                if ($(this).is(":checked")) {
                    href = href + "&ShowAllLinked=1";
                } else {
                    href = href + "&ShowAllLinked=0";
                }

                $('#ctl00_ContentPlaceHolder1_lnkAuditReport2').attr("href", href);
            }

        });

It worked like a charm!

"text/javascript">
    function BindControlEvents() {
        //jQuery is wrapped in BindEvents function so it can be re-bound after each callback.
        //Your code would replace the following line:
            $('#').limit('100', '#charsLeft_Instructions');
    }

    //Initial bind
    $(document).ready(function () {
        BindControlEvents();
    });

    //Re-bind for callbacks
    var prm = Sys.WebForms.PageRequestManager.getInstance();

    prm.add_endRequest(function() {
        BindControlEvents();
    });

Advertisements