Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC4 view is not detecting JQuery

I have a @Html.DropDownList which calls a jquery function. But it failed to call the function. I have 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

Whats wrong here?

like image 377
Sandy Avatar asked May 15 '13 09:05

Sandy


3 Answers

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

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

A few more possible errors:

  • jQuery is not referenced in the page. To check this, open firebug, chrome dev tools or IE dev tools and check whether you have any errors
  • A common error is to include the $(document).ready inside the view, and only reference jQuery at the bottom. This will generate an error because at that point $ is not known. Possible solutions:
    1. Move the code to an external file and reference that file after the jQuery inclusion
    2. Move your jQuery declaration to the head-section (not recommended as it will slow down the page load)
like image 114
Kenneth Avatar answered Nov 13 '22 12:11

Kenneth


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

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

u forgot that it is a class.

like image 26
Vond Ritz Avatar answered Nov 13 '22 12:11

Vond Ritz


You can also use following code.

$(document).ready(function () {
    $(".test").live("change",function () {
        alert("1");            
    });
});
like image 1
Vishal Gavle Avatar answered Nov 13 '22 12:11

Vishal Gavle