Search code examples
jquerybootstrap-4

Bootstrap 4 Loading Spinner in button


I'm trying to implement the bootstrap 4 loading spinner in button as in Bootstrap Spinners.

Below is what I'm doing in code

my.html

<form class="form-inline" id="topicForm" action="" method="POST">
  <input type="text" id="inputTopic" name="topic" class="form-control mb-2 mr-sm-2" placeholder="Topic of interest" required autofocus/>
  <button type="button" id="btnFetch" class="btn btn-primary mb-2">Submit</button>
</form>

my.js

$(document).ready(function() {
    $("#btnFetch").click(function() {
      // load data via AJAX
      fetch_data($("#inputTopic").val());
      // disable button
      $(this).prop("disabled", true);
      // add spinner to button
      $(this).html(
        `<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>Loading...`
      );
    });
});

This works except that the spinner as shown in bootstrap doc is not showing up. The button text is changing to Loading... as expected. Wanted to know what is that I'm not doing right to the spinner inside the button.

Code Pen here


Solution

  • You have to add Bootstrap 4.2.1 for this code while you are using 4.0

    $(document).ready(function() {
        $("#btnFetch").click(function() {
          // disable button
          $(this).prop("disabled", true);
          // add spinner to button
          $(this).html(
            `<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Loading...`
          );
        });
    });
    <link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css">
    
    <div style="margin:3em;">
      <form class="form-inline" id="topicForm" action="" method="POST">
        <input type="text" id="inputTopic" name="topic" class="form-control mb-2 mr-sm-2" placeholder="Topic of interest" required autofocus/>
        <button type="button" id="btnFetch" class="btn btn-primary mb-2">Submit</button>
      </form>
    </div>
    
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"></script>