Form submit confirmation made easy with jQuery

Say you have a form which executes an irreversible action like deleting a large data set. You want to add a confirmation prompt to make sure the user is fully aware of what they are about to do. Maybe there’s several buttons close together like a data grid with edit and delete buttons. A javascript confirmation prompt is the quickest way to accomplish this.

Just give any input submit button or anchor tag the class “confirm”, and a ‘title’ attribute with the confirmation message. As an added bonus, the title will appear as a tool tip when you hover over the button.

<input type=”submit” value=”Delete” title=”Do you really want to delete this?” />

Include the following javascript code and you’re all set. Easy, right?


var clickedInput;
$(document).ready(function () {
	$("input").click(function (event) {
		clickedInput = this;
	});

	$("form").submit(function () {
	    var confirmClick = $(clickedInput).hasClass("confirm");
	    if (confirmClick) {
	        var msg = $(clickedInput).attr("title");
	        if (!msg)
	            msg = "Are you sure you wish to perform this action?";
	        return confirm(msg);
	    }
	    return true;
	});
  
	$("a").click(function (event) {	
		clickedInput = this;
		var confirmClick = $(clickedInput).hasClass("confirm");
		if (confirmClick) {
			var msg = $(clickedInput).attr("title");
			if (!msg)
				msg = "Are you sure you wish to perform this action?";
		  
				var answer = confirm(msg);
				if (!answer)
					event.preventDefault();		
		}
		
	});
});

This entry was posted in javascript. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>