Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Bootstrap 3 modal for JavaScript alert()?

If I have an alert in my JavaScript code in the HTML header, such as:

<head>
...
<script>
    ...
    if (errors) {
        alert('The following error(s) occurred:\n' + errors);
    }
    ...
</script>
</head>

is there a way I can use a modal window from Bootstrap instead of the browser's native alert window?

If so, can someone show me a simple example for the one line of code I have above? The modal should just have an "OK" button (nothing fancy).

like image 437
ggkmath Avatar asked Jun 24 '26 11:06

ggkmath


2 Answers

Ues Bootbox.js It is a small JavaScript library which allows you to create programmatic dialog boxes using Twitter’s Bootstrap modals, without having to worry about creating, managing or removing any of the required DOM elements or JS event handlers.

Here’s the simplest possible example:

bootbox.alert("Hello world!", function() {
  Example.show("Hello world callback");
});

More details at Bootbox.js

like image 112
mnm Avatar answered Jun 26 '26 13:06

mnm


First, add the html for the modal with an id

<div id="alertModal" class="modal fade"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Errors Found!</h4> </div> <div class="modal-body"> <p></p> </div> <div class="modal-footer"> <button class="btn btn-default" data-dismiss="modal"> Close</button> </div> </div><!-- /.modal-content --> </div><!-- /.modal-dialog --> </div><!-- /.modal -->

Second, modify your javascript to set the content of the modal body and show it

<script>
...
if (errors) {
    var message = 'The following error(s) occurred:\n' + errors;
    $('#alertModal').find('.modal-body p').text(message);
    $('#alertModal').modal('show')
}
...
</script>
like image 27
Abimbola Esuruoso Avatar answered Jun 26 '26 12:06

Abimbola Esuruoso



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!