lassedev
lassedev

Reputation: 337

ASP.NET MVC - jQuery document.ready() function not called

I have a Razor view containing this script:

<script type="text/javascript">
    jQuery(function()
    {
        alert("hello world");
    })
</script>

The script doesn't open an alert Dialog when the page is loaded.

Portion of the BundleCfg:

bundles.Add(New ScriptBundle("~/bundles/jquery").Include(
            "~/Scripts/jquery-{version}.js",
            "~/Scripts/jquery.unobtrusive-ajax.js",
            "~/Scripts/jquery.validate.unobtrusive.js"))

bundles.Add(New ScriptBundle("~/bundles/jqueryval").Include(
            "~/Scripts/jquery.validate*"))

At the End of the Layout Body:

@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required:=False)

Upvotes: 1

Views: 17550

Answers (3)

The problem is that the jQuery library is loaded after the symbol $ (jQuery) is called; that's why is doesn't work.

You have to put the line:

@Scripts.Render("~/bundles/jquery")

before the body is rendered.

Upvotes: 1

vscorp1991
vscorp1991

Reputation: 42

Try this

$(document).ready(function() {
    alert("hello world");
});

here is details: https://learn.jquery.com/using-jquery-core/document-ready/

Acording to link on top I realized that your code:

<script type="text/javascript">
    jQuery(function()
    {
        alert("hello world");
    });
</script>    

is the same as this

<script type="text/javascript">
  $(document).ready(function() {
      alert("hello world");
  });
</script>

So problem was just about place where to render bundles.

Upvotes: 2

MaazKhan47
MaazKhan47

Reputation: 849

Change your code with this.

$(document).ready(function () {
        alert("Hello World");
 });

Upvotes: 0

Related Questions