With this code below, I get an error: $ is not defined
. My question is: How it is possible?
... <script type="text/javascript"> $(document).ready(function () { $(function () { $('#cb').click(function () { if (this.checked) { $('div#div').slideDown(); } else { $('div#div').slideUp(); } }); }) }); </script> @section Scripts { @Scripts.Render("~/bundles/jqueryval") } @Scripts.Render("~/Scripts/jquery-1.7.1.min.js") @Scripts.Render("~/Scripts/jquery-ui-1.8.20.min.js")
As we can see, it load properly all of scripts:
<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> <script src="/Scripts/jquery.unobtrusive-ajax.js"></script> <script src="/Scripts/jquery.validate.js"></script> <script src="/Scripts/jquery.validate.unobtrusive.js"></script>
How to resolve 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> }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With