View MVC4 does not detect jQuery

I have a @ Html.DropDownList that calls a jquery function. But he could not call the function. I tried -

$(document).ready(function () { $('.test').change(function () { alert("1"); }); }); @Html.DropDownList("PropertyContent", ViewBag.PropertyList as List<SelectListItem>, new { @class="test"}) 

and

 function test() { alert("1"); } @Html.DropDownList("PropertyContent", ViewBag.PropertyList as List<SelectListItem>, new { onchange="test();"}) @Scripts.Render("~/bundles/jqueryval") is also included in the view 

What is wrong here?

+7
source share
6 answers

Your jQuery selector is wrong, use the id selector instead:

 $(document).ready(function () { $('#PropertyContent').change(function () { alert("1"); }); }); 

A few possible mistakes:

  • There is no link on the jQuery page. To check this, open firebug, chrome dev tools or IE dev tools and check if you have any errors.
  • A common mistake is to include $ (document) .ready inside the view and only the jQuery link below. This will result in an error because $ not known at this point. Possible solutions:
    • Move the code to an external file and specify this file after jQuery is included
    • Move the jQuery declaration to the head section (not recommended, as this will slow down the page loading).
+4
source
 $(document).ready(function () { $('.test').change(function () { alert("1"); }); }); 

$('.test').change(function () { // in this part you need to add '.' to the test

u forgot that this is a class.

+3
source

You can also use the following code.

 $(document).ready(function () { $(".test").live("change",function () { alert("1"); }); }); 
+1
source

FIDDLE Working Demo

 $(function () { $('#PropertyContent').change(function () { alert("1"); }); }); 
0
source

Add the following line in the form or in the layout:

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

Also your selector is incorrect. You do not have an HTML element with class="test" .

Try $('#PropertyContent') instead.

0
source

Try to get dropDownList by its identifier, for example, the code below. I got a working example for you: http://jsfiddle.net/pzzQu/

 $(document).ready(function () { $('#PropertyContent').change(function(){ alert('1'); }); }); 
0
source

All Articles