0
votes

I'm trying to get a submit button to change to a loading spinner with the text "Loading..." using JavaScript like the image below.

enter image description here

I'm able to update the innerHTML for the button, but I'm having trouble changing the span class, which controls the actual spinner.

Here is my html for the button:

<button class="btn btn-primary mx-3" id="submit" onclick="loading()" type="submit">
  <span id="button_span"></span>
  Submit
</button>

And here is the JavaScript:

function loading() {
    var button = document.getElementById("submit");
    button.innerHTML = "Loading...";
    var span = document.getElementById("button_span");
    span.classList.add("spinner-grow");
    span.classList.add("spinner-grow-sm");
}

Any help would be greatly appreciated. Thanks.

2

2 Answers

1
votes

Here you have a working pen: https://codepen.io/cbrown___/pen/dyMKQQb

Using Jquery and Font-awesome. THere are many ways of doing this, but this is one of them.

HTML

<button class="btn btn-primary mx-3" id="submit" onclick="loading()" type="submit">
   <i class="fas fa-spinner fa-spin" style="display:none;"></i>
  <span class="btn-text">Submit</span>
</button>

.JS

function loading() {
  $(".btn .fa-spinner").show();
  $(".btn .btn-text").html("Loading");
  
}

Recommend also this solution: Bootstrap 4 Loading Spinner in button

0
votes

I don't think you should be changing the inner HTML or class of the button. Create a new span that is the loading animation but hidden by default with css prop display: none.

When the button get clicked hide the button by dynamically changing the css and show the span the same way. Then whenever the loading is done just flip it back.