I have an issue running with jquery 3.6.3 and I am using datatables.net-bs4
. (I am targeting bootstrap 4
)
I created a barebones Rails 7 App:
rails _7.0.4_ new rails7BStestapp -T --css=bootstrap -j esbuild
cd rails7BStestapp
yarn add jquery datatables.net-bs4
Then created a load_dependencies.js
file in app/javascript
that looks like:
import jquery from 'jquery'
import DataTable from "datatables.net-bs4"
window.jQuery = jquery
window.$ = jquery
window.DataTable = DataTable();
and finally in app/javascript/application.js
I added:
import "./load_dependencies.js"
After creating a simple controller
rails g controller home index
and going to localhost:3000/home/index
In the console I get:
application-ca1281b74271bb2669fc8d31a6756411b650c76d13311ce2fd4b9854109592f0.js:18137 Uncaught TypeError: this.each is not a function
at DataTable (application-ca1281b74271bb2669fc8d31a6756411b650c76d13311ce2fd4b9854109592f0.js:18137:10)
at application-ca1281b74271bb2669fc8d31a6756411b650c76d13311ce2fd4b9854109592f0.js:23743:22
at application-ca1281b74271bb2669fc8d31a6756411b650c76d13311ce2fd4b9854109592f0.js:23744:3
Any ideas?
2
Answers
Always use a fallback when loading data off a server, since array/object methods will throw an exception if used on
undefined
.For your case, you may wish to define
window.DataTable
like this instead:window.DataTable = DataTable() ? DataTable : [];
I got similar issue and my guess is that you have not included jquery in your package.json. Please add that and do
npm install
.Let me know if I can help further.