With this code below, I get an error: $ is not defined
. My question is: How it is possible?
...
You are including jquery twice.
<script src="/Scripts/jquery-1.7.1.min.js"></script>
<script src="/Scripts/jquery-ui-1.8.20.min.js"></script>
<script src="/Scripts/jquery-1.7.1.js"></script>
The first and the last js files are the same, except one is minified and the other is probably not. Remove the non-minified one and it should work for you.
You're not including the jQuery JS until the end of the page but you're trying to make use of $ well before you've included it.
You've placed your script in the view body and not inside the Scripts
section which is where it belongs and after referencing jQuery:
@section Scripts {
@Scripts.Render("~/Scripts/jquery-1.7.1.min.js")
@Scripts.Render("~/Scripts/jquery-ui-1.8.20.min.js")
@Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
$(function () {
$('#cb').click(function () {
if (this.checked) {
$('div#div').slideDown();
} else {
$('div#div').slideUp();
}
});
});
</script>
}
Also to avoid having referenced jQuery twice (as in your case) double check if you haven't included it already as a bundle in your _Layout
.
And one last remark: since by default scripts are included at the end of the DOM, just before the closing body tag, you don't need to be wrapping your script in a $(document).ready
simply because by the time it executes the DOM will already be loaded. Your code is even worse because you had it twice. Bear in mind that $(function() { ... });
is equivalent to $(document).ready(function() { ... });
and in your case you've nested 2 of those things when you actually don't need any of them.
So:
@section Scripts {
@Scripts.Render("~/Scripts/jquery-1.7.1.min.js")
@Scripts.Render("~/Scripts/jquery-ui-1.8.20.min.js")
@Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
$('#cb').click(function () {
if (this.checked) {
$('div#div').slideDown();
} else {
$('div#div').slideUp();
}
});
</script>
}