0

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>

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks.So are you saying your statement above should come before this line @using (Html.BeginForm()) in my code?
No, that's not what I am saying. What I said in my answer is to put your script inside the Scripts section. Where this section is placed in your view makes absolutely no difference. Yes, for readability you could place it at the top of the view. But what's important is where it will get displayed at runtime. In this case that would be just before the closing </body> tag. Look at your _Layout.cshtml file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.