Search code examples
asp.net-mvctwitter-bootstrapbootstrap-switch

How to initialize bootstrapSwitch()?


I am missing something simple, but can'T find it. In my asp.net MVC5 project, I want to use bootstrap-switch. This is what I've done:

BundleConfig.cs: added bootstrap-switch.css and bootstrap.switch.js as follows,

bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                  "~/Scripts/bootstrap.js",
                  "~/Scripts/respond.js",
                  "~/Scripts/bootstrap-switch.js"));

bundles.Add(new StyleBundle("~/Content/css").Include(
                  "~/Content/bootstrap.css",
                  "~/Content/bootstrap-switch.css",
                  "~/Content/site.css"));

(and made sure the files are at those locations).

Then, in a view I tried the following three checkboxes,

<input type="checkbox" class="switch" />
<input type="checkbox" class="switch" name="box" />
<input type="checkbox" 
    data-on-text="Option A"
    data-off-text="Option B"
    data-size="mini"
    name="box2" />

and added, at the bottom of the view file,

<script>
    $("[name='box']").bootstrapSwitch();
    $("[name='box2']").bootstrapSwitch();
</script>

But when I run the project, the checkbox looks like the standard checkbox (no CSS, or functions have been added).

I've read a lot of posts on this (my code follows http://www.bootstrap-switch.org/ verbatim), but can't find my mistake.


Solution

  • The problem was that if you include the js files in the bundle, it is rendered last on the page. Hence, if you use javascipt on your view that references a .js library loaded in the bundle, it does not work to put it at the end of the view file, rather render the scripts section,

    @section scripts{
        <script>
            $(".indent-1").css("background", "green");
        </script>
    }
    

    This will then appear on the html file after the libraries are imported.