mare
mare

Reputation: 13083

JavaScript on jQuery created code never gets called

This is my view in ASP.NET MVC.

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Administration.Master" Inherits="System.Web.Mvc.ViewPage" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="HeadContent" runat="server">
    <script type="text/javascript">

        var ddlContentTypes;

        $(document).ready(function () {
            ddlContentTypes = $("#ContentTypes");
            ddlContentTypes.bind("change", loadCreate);
            loadCreate();
        });

        function loadCreate() {
            var typeId = $("#ContentTypes option:selected").val();
            $.get('~/' + typeId + '/Create', function (data) {
                $("#CreateForm").html(data);
            });
            $("fieldset input").each(function (index, item) {
                $(item).attr("disabled", true);
            });
        }
    </script>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">
    <h2>
        <%=Resources.Localize.CreateWidget %></h2>
    <p>
        <% Html.RenderPartial("ContentTypeSelector"); %></p>
    <div id="CreateForm">
    </div>
</asp:Content>

As you can see, it loads some HTML (actually user control) and adds it to the CreateForm div. This actually works fine.

The problem is this

$("fieldset input").each(function (index, item) {
                $(item).attr("disabled", true);
            });

never runs. The fieldset tag is in the response, so you don't see it here but it's there - everything is returned back fine (I checked with Firebug).

Why do the above two lines of JS never run or have any effect?

Upvotes: 0

Views: 96

Answers (2)

hunter
hunter

Reputation: 63562

I think your problem is here:

$.get('~/' + typeId + '/Create', function (data) {
    $("#CreateForm").html(data);
});

should be:

$.get("<%=ResolveUrl("~/") %>" + typeId + "/Create", function (data) {
    $("#CreateForm").html(data); // thanks Peter
    $("fieldset input").attr("disabled", "disabled"); // thanks Nick
});

That's probably tossing a js exception and it's never getting to the fieldset loop.

Upvotes: 1

Peter
Peter

Reputation: 767

The fieldset tag doesn't exist when you call this code. Try moving this code to the inside of your success function and it might work.

function loadCreate() {
        var typeId = $("#ContentTypes option:selected").val();
        $.get('~/' + typeId + '/Create', function (data) {
            $("#CreateForm").html(data);
            $("fieldset input").each(function (index, item) {
                $(item).attr("disabled", true);
            });
        });
    }

Upvotes: 2

Related Questions