Joel
Joel

Reputation: 647

Getting jquery event to fire for element in ajax loaded partial view (bootstrap modal form)

I'm trying to figure out the correct approach for initializing jquery events referencing partial view elements loaded via ajax. Specifically I'm trying to use bootstrap-datepicker.js in a in a bootstrap modal form.

Background: Had a functioning page with datepicker working. Project for today was to convert that form to a bootstrap modal. A lot of what I did came from MVC 4 Edit modal form using Bootstrap

All that is working fine. Since I am now loading the partial view via ajax, datepicker doesn't work. I understand the problem, I just don't know the solution. Any advice appreciated.

Calling view has

<div class="modal hide fade in" id="addclassroom">
    <div id="classroom-container"></div>
<div>

<script type="text/javascript">
$(document).ready(function () {
    $('#addclassbtn').click(function () {
        var url = "/Quiz/[email protected]"; 
        $.get(url, function (data) {
            $('#classroom-container').html(data);
            $('#addclassroom').modal('show');
        });
    });
});
</script>

Controller:

public ActionResult AddClassroom(int quizId)
{
    var classroom = ...
    return PartialView("_AddClassroom",classroom);
}

Partial View:

@using (Ajax.BeginForm("AddClassroom", "Quiz", FormMethod.Post,
                    new AjaxOptions
                    {
                        //InsertionMode = InsertionMode.Replace,
                        HttpMethod = "POST",
                        UpdateTargetId = "addclassroom"
                    }))
    {
        @Html.ValidationSummary()
        @Html.AntiForgeryToken()
        <div class="modal-body">
            <fieldset class="QuizDisplayFields">
                *fields...etc*
                @Html.TextBoxFor(model => model.StartDate, new {@class="datefield" })
                @Html.ValidationMessageFor(model => model.StartDate)
                *more fields...*
                <input type="submit" class = "btn btn-primary" value="Save" />
            </fieldset>
        </div>
    }

<link href="~/Content/datepicker.css" rel="stylesheet" />
<script src="~/Scripts/bootstrap-datepicker.js"></script>

   <script>
    $(document).ready(function () {
        $("#StartDate").datepicker();
    });
   </script>
   <script>
       $(function ($) {
           $("#StartDate").on("click").datepicker();
       });
   </script>

Upvotes: 1

Views: 6152

Answers (1)

anpsmn
anpsmn

Reputation: 7257

$(document).ready won't work in a partial. It is only executed when the page is loaded initially.

So you need to shift those scripts, inside the partial, to the callback function of your ajax call.

Upvotes: 2

Related Questions