AI Bootstrap Builder Logo
AI Bootstrap Builder Questions & Answers

How do I add a spinner inside a button while a form submits?

Asked on Jun 30, 2025

1 Answer

To add a spinner inside a button during form submission, you can use Bootstrap's spinner component and JavaScript to toggle its visibility. Here's a simple example:
<!-- BEGIN COPY / PASTE -->
        <form id="myForm">
            <button type="submit" class="btn btn-primary" id="submitButton">
                Submit
                <span class="spinner-border spinner-border-sm d-none" role="status" aria-hidden="true" id="spinner"></span>
            </button>
        </form>

        <script>
            document.getElementById('myForm').addEventListener('submit', function(event) {
                event.preventDefault();
                var button = document.getElementById('submitButton');
                var spinner = document.getElementById('spinner');
                spinner.classList.remove('d-none');
                button.disabled = true;

                // Simulate form submission delay
                setTimeout(function() {
                    spinner.classList.add('d-none');
                    button.disabled = false;
                }, 2000);
            });
        </script>
        <!-- END COPY / PASTE -->
Additional Comment:
  • The spinner is initially hidden using the `d-none` class.
  • When the form is submitted, the spinner becomes visible, and the button is disabled to prevent multiple submissions.
  • A `setTimeout` function simulates a delay (e.g., for an AJAX call) and then hides the spinner and re-enables the button.
  • Replace the `setTimeout` with actual form submission logic as needed.
✅ Answered with Bootstrap 5 best practices.
← Back to All Questions