Search code examples
jqueryclickconfirmpropagation

Click Issue - Confirm Alert not preventing HREF clicks


I'm trying to accomplish the following:

When a user clicks outside of a div("productListMatch") containing checkboxes, if any of the checkboxes are checked, a confirm alert appears, letting the user know that they haven't saved there checkbox selection.

In short, I'm checking if a checked item is saved or not. If so, notify the user, giving them the option to save or not.

This is what I've done:

function formCheckboxConfirm() {
    $('html').click(function() {
        var elem = document.getElementById('frm-list-product').elements;
        for (i = 0; i < elem.length; i++) {
            if(elem[i].type == "checkbox" && elem[i].checked) {
                confirm("You have made changes! Do you want to proceed without saving your changes?");
                break;
            }
        }
});

    $(".productListMatch").click(function(e) {
        e.stopPropagation(); // I thought this would stop all link clicks, but it's not working as I expected.
    });
}

Although this works in general, it doesn't work with links. Once they're clicked, they continue to perform, and I still receive the confirm alert.

Note: There are a number of navigation links on the webpage outside of the div. The "productListMatch" div itself is a part of content within a jquery tab (2nd of two), so the tab has to be clicked just to see the "productListMatch" div.

What I'd like is this:

  • If any link - aside from the checkboxes (and the Save button) - is clicked
    • Stop link from performing
      • Perform check if checkboxes are checked or not
        • If a checkbox is checked, provide confirm alert
          • If user clicks "OK", webpage continues to link that was initially clicked
          • If user clicks "CANCEL", webpage does not continues to link that was initially clicked
        • If a checkbox is not checked, no confirm alert, and webpage continues to link that was initially checked

I tried couple of scenarios, and although I can get the links to stop (I used preventDefault), I'm uncertain as how to get them to start again. Perhaps I'm going about this whole thing wrong.

I would appreciate some assistance.

Thanks.

Stephen


Solution

  • The confirm() function returns a boolean you need to test. For instance:

    if confirm("You have made changes! Do you want to proceed without saving your changes?") {
       // continue or whatever 
    } else {
       return false; // or break or whatever
    }