Created by dan on Friday 20th November, 2009 at 3:56 PM
Tags: HTML, Javascript, jQuery, Web development
Following a little research, I found there to be no set solution for my problem, so I decided to sort it out myself and post the final solution here.
Simply put, I have a form with some checkboxes, which when ticked and posted, trigger deletion on the selected item. Using jQuery's loveliness, I managed to pull it off rather easily. I simply have the posted script loading on each page where a form exists. Of course, we don't want to check each and every form for checkboxes, so this is where we get a clever with it.
We set the form class to "handledel" and the class of the deletion checkboxes to "delitem". The script then looks out for forms with this class, checking each for the delitem-classed checkboxes. If any of the boxes are checked, it will confirm with the user that items are marked for deletion. If cancelled, the form will cease to submit. If no checkboxes are checked, it will carry on as it is.
As things stand, this only supports one set of deletion checkboxes per form, however it can be easily adapted if you want to take it to another level. Anyhow, I hope this helps someone.
/* <![CDATA[ */
// Upon the DOM being ready
$(document).ready(function() {
// Handle form submission
$('form.handledel').submit(function(e) {
// Define variables
var checkboxSelectionCount = 0;
var retval = true;
// Check if any checkboxes inside have been checked
$(this).find('input[type=checkbox].delitem:checked').each(function() { checkboxSelectionCount++; })
// If checkboxes are selected
if (checkboxSelectionCount > 0) {
// If confirmation returns false (customer would not like to continue)
if (!confirm('You have ' + checkboxSelectionCount + ' item' + (checkboxSelectionCount>1?'s':'') + ' marked for deletion, do you wish to continue?')) {
// Set retval to false (do not submit)
retval = false;
}
}
// If retval is false
if (!retval) {
e.preventDefault();
}
// Return retval
return retval;
});
});
/* ]]> */