I have created a Laravel 5.6 project on my local.
I have <script src="{{ asset('js/app.js') }}" defer></script>
in <head>
In one of the views, I tried
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery( "#ddtype" ).change(function() {
alert( "Handler for .change() called." );
});
});
</script>
but it gives me jQuery is not defined
error
If I try Bootstrap 4's collapse function, it works fine. Does that mean jQuery is already included?
I have done npm install
and npm run dev
My resources/js/app.js
requires bootstrap.js
which looks like (not full code but top few lines) as below
window._ = require('lodash');
window.Popper = require('popper.js').default;
/**
* We'll load jQuery and the Bootstrap jQuery plugin which provides support
* for JavaScript based Bootstrap features such as modals and tabs. This
* code may be modified to fit the specific needs of your application.
*/
try {
window.$ = window.jQuery = require('jquery');
require('bootstrap');
} catch (e) {}
Please advise. I have checked in different browsers to make sure no cache issues etc.
Update
My layouts/app.blade.php structure is like this -
<html>
<head>
....
<!-- Scripts -->
<script src="{{ asset('js/app.js') }}" defer></script>
....
</head>
<body>
<div id="app">
@include('layouts.nav')
<main class="py-4">
@yield('content')
</main>
</div>
</body>
</html>
and myview.blade.php
@extends('layouts.app')
@section('content')
.....
.....
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery( "#ddtype" ).change(function() {
alert( "Handler for .change() called." );
});
});
</script>
@endsection
jQuery loaded via your
app.js
, which is only loaded once the page is ready because of thedefer
attribute in your script tag.Your inline script tag where you call
jQuery(document).ready
is loaded as the page renders, therefore executed before theapp.js
has been loaded. Hence the error, since jQuery is not yet loaded at that time.To fix it, simply remove the
defer
attribute from the script tag.For more information about the defer attribute: https://www.w3schools.com/tags/att_script_defer.asp