JavaScript Confirm Modal using Bootstrap

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>

Comments

Elvis

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!

Joseph

Works perfect:)

Jana Sindelarova

How this can be implemented for forms ? maybe: $( "#dataConfirmOK" ).click(function() { $(ev).closest("form").submit(); });

Alvin Chesaro

This is great work. Thank you!