JavaScript Confirm Modal using Bootstrap
Published on August 21, 2012
By Pete Freitag
By Pete Freitag
Back in the olden days you might have added code like this to your form onsubmit, or an anchor to do a javascript confirmation box:
<a href="delete.cfm" onclick="return confirm('Are you sure you want to delete?');">Delete</a>
That works, but using onclick
is not elegant and can lead to major issues when trying to implement things like Content-Security-Policy headers.
Looking for a better way to do this? Here's how you can do this leveraging the Bootstrap modal control:
First I add some JS to my document ready event handler:
$(document).ready(function() { $('a[data-confirm]').click(function(ev) { var href = $(this).attr('href'); if (!$('#dataConfirmModal').length) { $('body').append('<div id="dataConfirmModal" class="modal" role="dialog" aria-labelledby="dataConfirmLabel" aria-hidden="true"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button><h3 id="dataConfirmLabel">Please Confirm</h3></div><div class="modal-body"></div><div class="modal-footer"><button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button><a class="btn btn-primary" id="dataConfirmOK">OK</a></div></div>'); } $('#dataConfirmModal').find('.modal-body').text($(this).attr('data-confirm')); $('#dataConfirmOK').attr('href', href); $('#dataConfirmModal').modal({show:true}); return false; }); });
Now to trigger this in my HTML, I just add a data-confirm attribute to an anchor tag:
<a href="delete.cfm" data-confirm="Are you sure you want to delete?">Delete</a>
JavaScript Confirm Modal using Bootstrap was first published on August 21, 2012.
If you like reading about javascript, bootstrap, twitter, modal, js, or confirm then you might also like:
- Getting Started with jQuery Mobile
- jQuery UI Autocomple IE 6 Select List z-Index Issues
- Using jQuery UI Autocomplete with Hidden ID's
- jQuery UI Sortable Tutorial
Discuss / Follow me on Twitter ↯
Tweet Follow @pfreitagComments
Works perfect:)
by Joseph on 03/17/2017 at 4:03:09 PM UTC
How this can be implemented for forms ?
maybe:
$( "#dataConfirmOK" ).click(function() {
$(ev).closest("form").submit();
});
maybe:
$( "#dataConfirmOK" ).click(function() {
$(ev).closest("form").submit();
});
by Jana Sindelarova on 04/13/2019 at 7:06:09 PM UTC
This is great work. Thank you!
by Alvin Chesaro on 02/21/2021 at 2:36:57 PM UTC
Do you could give me any advice how to use this method for my javascript confirms as well?
Example: if(confirm('blah blah'){ do this and that }
Greetings from Germany!