Search code examples
javascriptjquerywindowhrefpreventdefault

preventDefault() overruled by window.location


I have process in my website which contains a few steps. To navigate I have "previous" and "next" buttons. These buttons are <a> elements with an href attribute (to visit the previous and next step).

The next button works as a door to the next step, but also to validate some fields in the current step, before it continues.

So this is what happens when clicking the next button:

  1. The href value got saved in a variable $url.
  2. preventDefault() prevents the link from opening the URL.
  3. There are some validation checks done.
  4. If they return "true", the $url will be loaded in window.location.

For some steps I need to do another check to the user with a confirm box. But here comes the problem:

Problem:

When the confirm() returns "false", the user should not go to the next page. But the window.location of function 1 "overrules" the preventDefault() of function 2 now.

1. Default next button function:

$('#next_link').click(function(e) {
    var url = $(this).attr('href');
    e.preventDefault();             
    if(wiz_validate_required() && wiz_is_step_done()) {
        window.location = url;  
    } 
}); 

2. Confirm box function:

$('.dimensions-check').click(function(e) {
    if(confirm('Have you specified the dimensions in millimeters?') == false) {
        e.preventDefault();
    }
});

Solution

  • I would do something like that. If you have any question for the code please ask!

    fiddle

        // These can be changed for each step if you want or not a confirmation 
       var needs_confirm = true;
       var cb_message = 'Have you specified the dimensions in millimeters?';
    
       $('#next_link').click(function(e) {
    
         var url = $(this).attr('href');
         e.preventDefault();
    
         if (needs_confirm === true) {
           if (confirm_box(cb_message) === true) {
             redirect_window(url);
           }
         } else {
           redirect_window(url);
         }
    
       });
    
    
       function confirm_box(cb_message) {
         if (confirm(cb_message) === true) {
           return true;
         } else {
           return false;
         }
       }
    
       function redirect_window(url) {
         if (wiz_validate_required() && wiz_is_step_done()) {
           window.location = url;
         }
       }
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <div id="next_link"><a href="#">link</a>
    </div>