Hooking the onSwitchChange Event in Bootstrap Switch

Okay I’ll admit that this is a little on the arcane side but…it’s one of those things that when you need it, you need it.  I needed this info and spent way too much time trying to find something that worked.  I ultimately ended up going to GitHub and forking the repository just to find the proper syntax to capture this so I’m hoping this little tip will save you that bother.

The point of discussion here is the Bootstrap Switch component, which you can find described here:  https://www.bootstrap-switch.org/.  It’s a Bootstrappy-version of an input checkbox, but it is implemented as a toggle switch.  The UI part of it is very easy to use and well documented on the site above.  If you haven’t seen them before they’re pretty cool and flexible too; here’s a screen shot of some of their examples:

Having the toggle functionality is quite nice, but of course you often are going to want to take an action of some sort when the toggle state is changed.  This is where the onSwitchChange event comes in…or perhaps it doesn’t – and this is a big part of the confusion.  The documentation describes the event as the onSwitchChange event, but there really isn’t such an event you can attach as an inline attribute.  Instead you have to use the funkier jQuery syntax for attaching to the Switch implementation of the event.  So what does all of that mean?  An example is worth a thousand words, so here you go:

<input type=”checkbox” name=”toggleChk”>


$(‘input[name=”toggleChk”]’).on(‘switchChange.bootstrapSwitch’, function (event, state) {
//console.log(this); // DOM element
//console.log(event); // jQuery event
//console.log(state); // true | false

Of course you will also need references in your page to the CSS and JS files that Switch requires, and that is covered on the Bootstrap Switch home page linked to above.  In any case, should you use this component now you have the additional goo you need to hook into the event when the value is toggled – hope that helps.