Question

So I have a Url.ActionLink, that when clicked, I want to load a partial view into a modal. This works the first time, but the second time it redirects the browser to the partial view instead of loading it into a modal, and the modal() call has an error saying that it is undefined.

The html for the div is:

        <div class="modal fade" id="modal">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-body" id="modalBody"></div>
                </div>
            </div>
        </div>

The code for the binding/loading so far is:

$(".actionLink").on("click", function (e) {
        e.preventDefault();
        $("#modalBody").load(e.target.href);
        $("#modal").modal('show');
        return false;
    });

The error that I'm getting before the redirect is on the $("#modalBody").load(e.target.href); and the error is "Uncaught TypeError: undefined is not a function." It works the first time a link is clicked, so I don't know why it would be undefined the second time.

Was it helpful?

Solution

The .on() type of binding works only with the elements which was created before the script has been initialised.
So if you load some content dynamically in the on click function, the on() binding won't work for that content.
One solution could be if you bind the click event to the container element, where you load the new content, something like this:

     $("#container").on("click", ".actionLink", function(e) { ... });


"Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on()" jQuery .on() doc

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top