Andy Johnson
Andy Johnson

Reputation: 693

jQuery html javascript not firing after setting html

I have a issue where I am setting an HTML to the DOM through jQuery html() method. When my content is loaded, there is a link in it and I am capturing that link vie jQuery on Click method but that doesn't see to be working. Please refer to the screenshot below. First screenshot is where page is loaded for the first time. jQuery on click method works just fine.

where page is loaded for the first time and Edit address link clicked

Address edit is loaded via jQuery AJAX and replaced the original DOM content via jQuery html() method

Address is saved and loaded back via jquery's html() method

Here is my onclick method

$(document).ready(function () {
    $("a.editAddressLink").on('click', function (e) {
                e.preventDefault();
                alert('editAddressLink clicked');
                var url = this.href;
                var dataObject = {};
                CustomAjaxRequest("Get", url, dataObject, "text", "HandleEditAddress", null, true);
                return false;
            });
        });
});

function HandleEditAddress(data) {
        $("#addressDisplay").fadeOut(1000, function() {
            $(this).html('<div class = "panel-body">'+data+'</div>').fadeIn(1000);
            if ($('#AddressType').length && $('#AddressType').val() != "") {
                $('#AddressTypeslist').val($('#AddressType').val());
            } else {
                $('#AddressTypeslist').val('');
            }
            $('#AddressTypeslist').trigger('change');
            $('#addressDisplay').css('display', '');
        });

        //$("#addressDisplay").html(data);

    }

and now when I click on the edit link, the function to handle the click doesn't fire. I made sure looking at the source that function is available to the DOM all the time since I don't do any page refreshes.

Any help will be appreciated. Thanks

Upvotes: 0

Views: 31

Answers (1)

The Alpha
The Alpha

Reputation: 146191

You should use a delegated event handler like this:

$(document).on('click', 'a.editAddressLink', function (e) {
    // ...
});

Upvotes: 2

Related Questions