Ethan Pelton
Ethan Pelton

Reputation: 1796

jquery not firing in content loaded via ajax

This function works normally, but not if the content was loaded via ajax...

    $(function () {
        $('#defid_527209').on('change', function () {
            $('#formdef_527209').submit();
        });
    });

Nothing happens on click. The event does not fire - no network or client side errors.

The html that get's loaded...

<form action="/booking/UpdateDefinite" data-ajax="true" data-ajax-method="POST" data-ajax-success="definiteupdated" id="formdef_527209" method="post"><input data-val="true" data-val-number="The field leadid must be a number." data-val-required="The leadid field is required." id="bookingleadhistory_leadid" name="bookingleadhistory.leadid" type="hidden" value="527209" />    Definite: 
<input data-val="true" data-val-required="The definite field is required." id="defid_527209" name="bookingleadhistory.definite" type="checkbox" value="true" /><input name="bookingleadhistory.definite" type="hidden" value="false" /></form>
    <script>
        $(function () {
            $('#defid_527209').on('change', function () {
                $('#formdef_527209').submit();
            });
        });

        function definiteupdated(d) {
            console.log('logged:' + d);
            if (d == "True") {
                if ($('#defcheck').length == 0) {
                    $('#defcheckhack').css("display", "inline");
                }
            } else {
                $('#defcheck').css("display", "none");
                $('#defcheckhack').css("display", "none");
            }
        }
    </script>

The html is not present in Chrome sources tab until after page refresh.

Upvotes: 2

Views: 58

Answers (1)

taxicala
taxicala

Reputation: 21769

You problem is with event delegation, you will have to tell a preexisting container to delegate the event for you:

$(function () {
    $('body').on('change', '#defid_527209', function () {
        $('#formdef_527209').submit();
    });
});

When you attach an event to an element, if it's not present at the time your js code runs, it will never get the event. This way, with event delegation, you are telling body (in this case) to delegate the event to all '#defid_527209' elements. So, the event is really attached to the body, but when an element with that id is appended to the DOM, that element will receive the event from it's parent ('body') in this case.

Upvotes: 4

Related Questions