Wednesday, October 01, 2014

jQuery $.ajax call add functions you will need to call after the html is rendered.

I am adding the following blog post because I spent a good amount of time working on figuring the following out.

Using the jQuery function $.ajax I learned that you need to be sure to add all the functions you want to perform actions on after the $.ajax loads the new content to the page.

CORRECT CODE
<script type="text/javascript">
    $("#addItem").click(function () {
        $.ajax({
            url: this.href,
            cache: false,
            success: function (html) {
                $("#editorRows").append(html);
                $("a.deleteRow").on("click", function () {
                    $(this).parents("div.editorRow:first").remove();
                    return false;
                });
            }
        });
        return false;
    });

</script>

This makes 100% sense because if you code it as follows it will never work because the .append(html) is not on the page currently when the jQuery loads.

BAD CODE
<script type="text/javascript">
    $("#addItem").click(function () {
        $.ajax({
            url: this.href,
            cache: false,
            success: function (html) {
                $("#editorRows").append(html);
            }
        });
        return false;
    });

//Following will not be called --- because it is not on the page currently
    $("a.deleteRow").on("click", function () {
        $(this).parents("div.editorRow:first").remove();
        return false;
    });
</script>


Hope this helps.  Have fun coding.

Post a Comment