Bootstrap Switch fn is not a function

Tom Hammond picture Tom Hammond · Mar 19, 2017 · Viewed 9.4k times · Source

I'm trying to add bootstrap switch to a rails project. When I add my script from here as this:

<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-switch/3.3.4/js/bootstrap-switch.js" data-turbolinks-track="true"></script>

I end up getting an error in the console:

Uncaught TypeError: Cannot read property 'fn' of undefined
    at bootstrap-switch.js:743
    at bootstrap-switch.js:19
    at bootstrap-switch.js:22

And the fn that's highlighted red as an issue is here:

$.fn.bootstrapSwitch = function (option) {
    for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
      args[_key2 - 1] = arguments[_key2];
    }

Any ideas why that isn't found? Or does anyone have a link to a bootstrap-switch.js file that I can use that will work?

Thanks!

I also tried using the bootstrap-switch gem but that was giving me a different error.

Answer

Nuhil Mehdy picture Nuhil Mehdy · Mar 19, 2017

Most common reason behind this type of error is, not having JQuery loaded before this plugin script. Make sure you have added that CDN version of bootstrap-switch.js after the JQuery.

I mean like following:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-switch/3.3.4/js/bootstrap-switch.js" data-turbolinks-track="true"></script>