How can I display an error message using Bootstrap instead of using JavaScript’s alert()?

Solution

The built-in alert() in JavaScript:

1. Cannot be styled.

2. Looks different across browsers.

3. Blocks execution until dismissed.

If you want a styled alternative, use Bootstrap Alerts or Modals.

Using Bootstrap Alerts


<div id="errorMessage" class="alert alert-danger" style="display: none;" role="alert">
  Something went wrong! Please try again.
</div>

<script>
  function showError() {
    document.getElementById("errorMessage").style.display = "block";
  }
</script>

Use this if you want a non-blocking inline error message.

Using Bootstrap Modals


<!-- Modal -->
<div class="modal fade" id="errorModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header bg-danger text-white">
        <h5 class="modal-title">Error</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        Something went wrong! Please try again.
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

<script>
  function showErrorModal() {
    var errorModal = new bootstrap.Modal(document.getElementById('errorModal'));
    errorModal.show();
  }
</script>