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>


Related Entries

11 people found this page useful, what do you think?

Trackbacks

Trackback Address: 809/A35B61202B735343C346DE983FCE4126

Comments

On 03/12/2013 at 6:51:41 AM UTC Elvis wrote:
1
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!

On 06/03/2014 at 9:09:51 PM UTC Anonymous wrote:
2
Thanks! This works well.

Post a Comment




  



Spell Checker by Foundeo

Recent Entries



foundeo


did you hack my cf?