Search code examples
javascriptconfirm

if confirm ignores location.href


The following code reloads the page rather than the desired URL

    function delFile(name,id) {
    if (confirm('Are you sure you want to DELETE '+name+'?')) {
        location.href='/cgi-bin/cnc.cgi?phrsrg~038919718485478~'+id ;
        alert('/cgi-bin/cnc.cgi?phrsrg~038919718485478~'+id);
    }
    else {
        return false;
    }
}

In the alert, the id is shown as being added properly and the URL is correct. I can copy it from the alert, then use that text to get the right result. Other scripts on the same page that use similar location.href are working perfectly but this is the only one using confirm.

I've also tried

window.location.href = "http://stackoverflow.com";

But the page still reloads.

The triggering link is:

onClick="return delFile('Bill','1234')

Solution

  • The href on the triggering link is still being linked to, because delFile() only returns false if the confirm is not accepted -- that's what's causing the page reload. When the function returns true, the link fires before the redirect occurs.

    You want the function to return false in all cases, so don't put the return in an else clause.

    function delFile(name, id) {
      if (confirm('Are you sure you want to DELETE ' + name + '?')) {
        location.href = '/cgi-bin/cnc.cgi?phrsrg~038919718485478~' + id;
        alert('/cgi-bin/cnc.cgi?phrsrg~038919718485478~' + id);
      }
      return false; // always, since you always want to prevent the link's default behavior.  (Could also use event.preventDefault here.)
    }
    <a href="/" onClick="return delFile('Bill','1234')">test</a>