The functionality of Bootstrap toggle ceases to operate properly following an AJAX content update

I am currently using AJAX load to fetch some content on my webpage. I am working with Bootstrap 3 and Bootstrap toggle. When the content is loaded, the Bootstrap 3 content functions properly (the panel-primary panel is clearly visible). However, the Bootstrap toggle content does not load (only some checkboxes are displayed). Does anyone have any suggestions on how to resolve this issue and get it functioning correctly? Alternatively, should I consider using different toggle switches? If so, which ones would be recommended?

EDIT: I haven't tested event binding yet because I am unable to get the Bootstrap toggle CSS to work on the AJAX-loaded code. Is event binding unrelated to the CSS?

  1. Scripts utilized by the main HTML code (the one with AJAX load)
  2. Main HTML code
  3. Code being loaded into a div by the main HTML code

<!-- jQuery -->
<script src="../bower_components/jquery/dist/jquery.min.js"></script>

<!-- Bootstrap Core JavaScript -->
<script src="../bower_components/bootstrap/dist/js/bootstrap.min.js"></script>

 <!-- Bootstrap Toggle JavaScript -->
<script src="../bower_components/bootstrap-toggle-master/js/bootstrap-toggle.min.js"></script>

<!-- Metis Menu Plugin JavaScript -->
<script src="../bower_components/metisMenu/dist/metisMenu.js"></script>

<!-- Custom Theme JavaScript -->
<script src="../dist/js/sb-admin-2.js"></script>

<!-- Custom Domotica JavaScript -->
<script> $(document).ready(function(){
        // Set trigger and container variables
        var trigger = $('#side-menu li ul li a'),
        container = $('#page-wrapper');
        
        // Fire on click
        trigger.on('click', function(){
            
          // Set $this for re-use. Set target from data attribute
          var $this = $(this),
            target = $this.data('target');       
            alert("target: " + target)
          // Load target page into container
          container.load(target + '.html', function (response, status, xhr) {});
          // Stop normal link behavior
          return false;
        });
      });
</script>
<!DOCTYPE html>
<html lang="en">

<head>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta name="description" content="Home automation web page">
  <meta name="author" content="">

  <title>Home</title>

  <!-- Bootstrap Core CSS -->
  <link href="../bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">

  <!-- Bootstrap toggle -->
  <link href="../bower_components/bootstrap-toggle-master/css/bootstrap-toggle.min.css" rel="stylesheet">

  <!-- MetisMenu CSS -->
  <link href="../bower_components/metisMenu/dist/metisMenu.min.css" rel="stylesheet">

  <!-- Custom CSS -->
  <link href="../dist/css/sb-admin-2.css" rel="stylesheet">

  <!-- Custom Fonts -->
  <link href="../bower_components/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">

  <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
  <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
  <!--[if lt IE 9]>
        <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
        <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
        <![endif]-->

</head>

<body>

  <div id="wrapper">

    <nav class="navbar navbar-default navbar-static-top" role="navigation" style="margin-bottom: 0">
      <div class="navbar-header">
        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
          <span class="sr-only">Toggle navigation</span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
        </button>
        <a class="navbar-brand" href="index.html">Home</a>
      </div>

...

        </div>
    </div>

    <div class="panel panel-primary" id="switchespanel">
          <div class="panel-heading">
            <h3 class="panel-title">Switches</h3>
        </div>
        <div class="panel-body">
            <table class="table">
                <tr>
                    <th>Location</th>
                    <th>State</th>
                </tr>
                <tr>                
                <td>Testswitch0</td>
                    <td>
                        <label>
                            <input type="checkbox" data-toggle="toggle" data-onstyle="success" id="S0" data-size="mini">
                        </label>
                    </td>                 
                </tr>   
            </table>
        </div>
    </div>

Answer №1

Double-check that you have correctly loaded both the bootstrap-toggle javascript and css files. Ensure they are located where your links point to, or consider using the cdn versions provided below:

<link href="https://gitcdn.github.io/bootstrap-toggle/2.2.0/css/bootstrap-toggle.min.css" rel="stylesheet">
<script src="https://gitcdn.github.io/bootstrap-toggle/2.2.0/js/bootstrap-toggle.min.js"></script>

If your paths are incorrect or if you forgot to include the js file entirely, there should be a warning in your console. Otherwise, the code should function properly.

Concerning dynamically generated content.

The initial elements work because, upon the page loading, bootstrap-toggle.min.js scans for any elements with the attribute data-toggle="toggle" and applies the plugin by calling .bootstrapToggle() on them. This process only occurs during the page load.

If you add more toggles later, you will need to initialize them manually using .bootstrapToggle(). Below is an updated example demonstrating how to simulate dynamically adding toggles and outlining the approach to take when doing so. Refer to the comments within the code for more information.

// timeout to mimic ajax
setTimeout(function(){ 
   // dynamically add an element,
  $('.table').append('<tr><td>Testswitch0</td><td><label><input type="checkbox" data-toggle="toggle" data-onstyle="success" id="S2" data-size="mini"></label></td></tr>');
    
    // now that we have dynamically added elements
    // we must initialize all new toggles
    // avoid re-initializing existing toggles
    // instead of searching for specific ones,
    // we'll remove all toggles and recreate them
    $("[data-toggle='toggle']").bootstrapToggle('destroy')                 
    $("[data-toggle='toggle']").bootstrapToggle();
  
}, 2000)
      
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link href="https://gitcdn.github.io/bootstrap-toggle/2.2.0/css/bootstrap-toggle.min.css" rel="stylesheet">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://gitcdn.github.io/bootstrap-toggle/2.2.0/js/bootstrap-toggle.min.js"></script>
<div class="panel panel-primary" id="switchespanel">
  <div class="panel-heading">
    <h3 class="panel-title">Switches</h3>
  </div>
  <div class="panel-body">
    <table class="table">
      <tr>
        <th>Location</th>
        <th>State</th>
      </tr>
      <tr>
        <td>Testswitch0</td>
        <td><label>
            <input type="checkbox" data-toggle="toggle" data-onstyle="success" id="S0" data-size="mini">
          </label></td>
      </tr>
      <tr>
        <td>Testswitch0</td>
        <td><label>
            <input type="checkbox" data-toggle="toggle" data-onstyle="success" id="S1" data-size="mini">
          </label></td>
      </tr>
    </table>
  </div>
</div>

Answer №2

Here is the most effective solution:

1- To ensure proper functionality, load Jquery before bootstrap. Arrange them in this order: Jquery first, Ajax second, and bootstrap last.

    <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/gh/gitbrent/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="791b16160d0a0d0b18094d540d161e1e151c394a574f5748">[email protected]</a>/js/bootstrap4-toggle.min.js"></script>

2- Trigger the function bootstrapToggle after an ajax request completes:

    $(document).ajaxComplete(function() {
        $('input[type=checkbox][data-toggle^=toggle]').bootstrapToggle();
    });

3- Important: Make sure to call your custom jquery script at the end for optimal performance.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Splitting HTML content into nodes using PHP XPath (including empty nodes)

I am currently attempting to separate the HTML string into individual nodes, along with their text content if applicable. Here is the HTML string that I am working with: <p>Paragraph one.</p> <p><strong>Paragraph <em>two</ ...

Choose the currently active md-tab within the md-dialog's md-tab-group

I need to create a dynamic md-dialog with an md-tab-group that has two tabs. The md-dialog should open based on the button clicked, displaying the corresponding tab content. The initial template where the md-dialog is triggered: <button md-button class ...

Learn how to implement pagination in AngularJS using the $http service

I need assistance in implementing pagination using Angularjs within the Ionic Framework. Can someone provide guidance on how to code pagination for fetching data from a JSON URL? controller.js angular.module('starter.controllers', []) .control ...

Attempting to access a shared php/javascript library using mod_rewrite

Let's dive into a fresh perspective on a question I previously raised: I've crafted a mod_rewrite snippet that checks for the existence of JavaScript, CSS, and PHP files on the subdomain they are called from (e.g., subdomain.example.com). If the ...

Encountered an issue while trying to access the 'value' property from an undefined field in the available options

When attempting to showcase the value of the select field, I encountered this error message: Cannot read properties of undefined (reading 'value') https://i.stack.imgur.com/Q0d2k.png You can find the codesandbox link here: https://codesandbox.i ...

The font color in Bootstrap is set to be lighter than the background color

Bootstrap has made great improvements in displaying navbar item colours that blend well with the background colour of the navbar. Can we apply a similar technique to body text as well? For example, if the container background is purple, can we have the t ...

Using jQuery to extract a specific row from a dynamic table cell within an AJAX JSON operation

My challenge is to correctly identify a selected table row based on the button clicked within a table cell that has been generated from a string using jQuery, with the button class as the selector. I have browsed through similar questions and adjusted my ...

It is important to ensure that the user returned by the onAuthStateChanged function in

server admin.auth().createCustomToken(uuid) .then((customToken) => { admin.auth().createUser({ email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ed989e889fad88958c809d8188c38e8280">[email protected] ...

Locate a Sub-Child href Element using Selenium

I am attempting to interact with a link using Selenium automation tool. <div id="RECORD_2" class="search-results-item"> <a hasautosubmit="true" oncontextmenu="javascript:return IsAllowedRightClick(this);" class="smallV110" href="#;cacheurl ...

The justify-content property aligns single-line text horizontally, but its alignment may not be consistent when the text expands over

Seeking a deeper understanding of flexbox alignment, I decided to experiment with aligning content using only flexbox properties. One puzzling observation is how "justify-content" centers items with single lines of text (flex-item-1 and flex-item-5), but n ...

Switching hamburger menu icons in Vue.js

I am trying to change a hamburger menu icon in my header to a cross icon when it is clicked. I have created a function in the computed property of my Vue template, but I'm not entirely sure about the implementation. How can I achieve this? Below is t ...

Div sliding out of view

I'm encountering a slight issue with this template: essentially, my goal is to implement a feature where clicking on a box will expand it while simultaneously sliding the other boxes off-screen. However, instead of just sliding the div off-screen, it ...

What is the best way to update my component when the selected value is changed?

Currently, I am facing an issue with my map component. It plots polyline data based on the option selected from the select menu component. The problem arises when I change the value in the select menu and click the play button for the animation. Instead of ...

What is the process for transforming a string into a Cairo felt (field element)?

In order to work with Cairo, all data must be represented as a felt. Learn more here Is there a way to convert a string into a felt using JavaScript? ...

Is SqliteDataReader not compatible with C#?

Currently, I am facing an issue with displaying data from a SQLite database on a web page using C#. Despite my efforts to find a solution and only coming across the console.writeline method, the SqliteDataReader function is not functioning properly. Below ...

Can you explain the distinction between using router.METHOD() versus router.route() in Express?

There are two different ways I've come across of writing this code. router.get(path, callback) and router.route(path).get(callback) Based on the surrounding code, they seem to have the same functionality. The documentation for these methods can be ...

Incorporate Subtitles into Your Website Using JWPlayer

I want to incorporate Video Captions similar to those seen on Lynda.com, for example at The captions should synchronize with the player and also appear in a separate block of HTML below the player. I am using JWPlayer for my video and have successfully in ...

How to create a calendar selection input using PHP?

Before I start writing the code myself, I am searching to see if there is already a solution available or if someone has previously outsourced the code. Below is an example of my date selection: I want to create a feature where selecting a month will aut ...

Is there a way to customize the design of an HTML scrollbar to resemble the one often seen on Google search engine result pages

While casually browsing online, I stumbled upon something truly unique. The image below shows a Google search result in Firefox that I have never encountered before or since. This screenshot captured a search result that was scrollable within itself. Isn& ...

Add the scss file to the vuejs component npm package only if certain conditions specified in the project are met

Creating css/scss themes for my Vue Components Npm package has been a focus of mine lately. This particular package is local and currently being tested using npm link. Both the Package and Project are utilizing webpack. index.js of Package import "./src ...