Pete Freitag Pete Freitag

JavaScript Confirm Modal using Bootstrap

web

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>

Like this? Follow me ↯

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:

Comments

Perfect, works like a charm as a replacement for the onclick="return confirm(...

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!
by Elvis on 03/12/2013 at 6:51:41 AM UTC
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();
});
by Jana Sindelarova on 04/13/2019 at 7:06:09 PM UTC

Post a Comment