Daria Korosteleva
Daria Korosteleva

Reputation: 171

Asp.Net MVC JavaScript doesn't work after loading page

I'm developing Asp.Net MVC application. I'm using partial view for menu in Layout form for some views. I need use JavaScript on this view, but its work only on first time - after view loaded. Later - doesn't. Partial View is like this:

@Scripts.Render("~/bundles/jquery")
@Html.CheckBox("IsChoosed", true, new { onclick = "FormReload();" })

<script>
    $(".IsChoosed").on("onchange", function () {
        FormReload();
    });

    var FormReload = new function ()
    {
        alert("FormReload");
    };

</script>

LayoutForm:

@Html.Partial("_ViewPartial")

@RenderBody()

Alert message is displayed after loading of page, when checkbox value set. But after while i'm changing value - doesn't. I tried to move JavaScritp methods to ***.js file and hook up it in view, but its worked the same way. Where can be an error?

Upvotes: 2

Views: 1133

Answers (2)

BenG
BenG

Reputation: 15164

Your change event is not firing because you are trying to attach to the class .IsChoosed.

try changing your change handler to:-

$("#IsChoosed").on("onchange", function () {
     FormReload();
});

so #IsChoosed instead of .IsChoosed.

EDIT

Also, change:-

var FormReload = new function ()

to this:-

function FormReload()

Upvotes: 1

xZ6a33YaYEfmv
xZ6a33YaYEfmv

Reputation: 1816

@Html.CheckBox("IsChoosed",... - first argument is name.

Selector $(".IsChoosed") looks for class IsChoosed. So onchange callback is not set.

To fix you can do the following:

@Html.CheckBox("IsChoosed", true, new { @class="IsChoosed", onclick = "FormReload();" })

Upvotes: 0

Related Questions