Sayan Patel
Sayan Patel

Reputation: 29

tablesorter is not a function rails 6 error

I am trying to add tablesorter to my tables but I end up with the following error on the browser console. Uncaught TypeError: n(...).tablesorter is not a function Here is my application.js:

// This file is automatically compiled by Webpack, along with any other files
// present in this directory. You're encouraged to place your actual application logic in
// a relevant structure within app/javascript and only use these pack files to reference
// that code so it'll be compiled.

import Rails from "@rails/ujs"
import * as ActiveStorage from "@rails/activestorage"
require('jquery')
import "channels"
import "cocoon";
import "chartkick/chart.js"
import tablesorter from 'tablesorter/dist/js/jquery.tablesorter'
Rails.start()
ActiveStorage.start()

import 'bootstrap/dist/js/bootstrap'
import 'bootstrap/dist/css/bootstrap'
import '../stylesheets/application'
import "@fortawesome/fontawesome-free/js/all"

require("stylesheets/application")

$(function () {
    $('.tablesorter').tablesorter({
    showProcessing: true,
    // initialize zebra and filter widgets
    widgets: ["zebra", "filter"],
    headers: {
      0: { sorter: false, filter: false },
      13: { sorter: true, filter: true }
    }
  });
})

I have added the gem in the Gemfile jquery-tablesorter. I have also done yarn add jquery and yarn add tablesorter but I am still stuck.

Note: jquery-tablesorter is the only gem related to jquery that I have in my Gemfile.

Upvotes: 1

Views: 258

Answers (1)

Alex
Alex

Reputation: 29964

I'm not sure where $ is being loaded here. Tablesorter doesn't have access to it to define tablesorter function. You need to explicitly import it.

import jQuery from "jquery";
import "tablesorter/dist/js/jquery.tablesorter";
window.$ = window.jQuery = jQuery;

or

window.$ = window.jQuery = require("jquery");
require("tablesorter/dist/js/jquery.tablesorter");

Upvotes: 1

Related Questions