Chaitanya
Chaitanya

Reputation: 7

Unable to use jquery in my mvc .net project

I've just started working with ASP.Net MVC4 project. I want to work with jQuery for click events in my project, but I am unable to get success even when I included jQuery in my layout.cshtml and Index(home) pages as follows,

Index(home):

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

 $("#searchId").click(function () {
        alert("Serach was clicked.");
    });

Layout.cshtml:

<body>
    @Scripts.Render("~/bundles/jquery")

  <p><input type="button" value="search" id="searchId" /></p>
</body>

Can anybody help me please to get a solution?

Upvotes: 1

Views: 50

Answers (2)

Rakib
Rakib

Reputation: 643

First thing is, you are rendering Jquery bundle 2 times both in Index and Layout page.

As Layout.cshtml is a master page so you have to put Jquery bundle only in master page not in the child index page.

And in the child index page just use following code:

$(document).ready(function(){
   $("#searchId").click(function () {
    alert("Serach was clicked.");
   });
 });

or

$( "#searchId" ).on( "click", function() {
  alert("Serach was clicked.");
});

Let me know if you still have the problem.

Upvotes: 0

Liviu Boboia
Liviu Boboia

Reputation: 1754

Your DOM might not be ready when you are registering the event handlers, try encapsulating the event handlers in document ready like this

 $(document).ready(function(){
    $("#searchId").click(function () {
        alert("Serach was clicked.");
    });
 });

Also I don't see the @RenderBody() method being called in your layout, that might give you an error too.

Upvotes: 2

Related Questions