Baba
Baba

Reputation: 2219

Unable to run jquery click event in mvc application

I have the code below in my index page for my home controller. I am new to Jquery. When I click the button, nothing happens. I expect to get the alert. What am I doing wrong?

    @{
        ViewBag.Title = "Home Page";
    }
    @section featured {
        <section class="featured">
            <div class="content-wrapper">
                <hgroup class="title">
                    <h1>@ViewBag.Title.</h1>
                    <h2>@ViewBag.Message</h2>
                </hgroup>
                <p>
                    Zombie's Page
                </p>
            </div>
        </section>
    }

    @using (Html.BeginForm())
    {
        <input type="submit" value="Click me" id="clickme" />

    }

    <script type="text/javascript">

        $("#clickme").click(function () {
            alert("Getting ready for practice !!");
        });

    </script>

Upvotes: 0

Views: 135

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038830

You should place your script in a Scripts section to ensure that it is rendered after the jQuery declaration:

@section Scripts {
    <script type="text/javascript">
        $("#clickme").click(function () {
            alert("Getting ready for practice !!");
        });
    </script>
}

The reason why your code didn't work is because it was rendered in the middle of the body, whereas jQuery is included at the end. Look at the _Layout.cshtml file.

Just open your browser debugger toolbar and look at the Console. In your case there would be an error stating that $ is undefined. Also look at the generated markup in the browser to see the difference between your code and mine.

Upvotes: 1

Related Questions