Redirect Using jQuery

28,925

Solution 1

You can use the window.location to redirect a browser:

https://developer.mozilla.org/en/DOM/window.location

Solution 2

You can use JavaScript's native window.location

$('#link').click(function(){  

    if(validation_fails) {
        window.location="http://this.site.com/";
    }
    else {
        return true;
    }
}

Solution 3

You can hash the div id to the window.location to display the div. Something like:

$(#link).click(function(){  
  if(validation_fails) window.location += "#<YOUR_DIV_ID>" ;  
  else return true;
}

Solution 4

$(#link).click(function(){  
  if(validation_fails){
    var loc = window.location;
    window.location = loc.protocol+"//"+loc.hostname+loc.pathname+"#somedivid";
  } else return true;
}

You need the extra code beyond @Cybermate's answer because otherwise you'll keep appending the hash each time it fails, e.g. "http://foo.com/bar#whee", then ""http://foo.com/bar#whee#whee", etc.

Edit: If the port might be used, you can conditionally include it:

window.location = loc.protocol + "//" + loc.hostname +
                  (loc.port && ":"+loc.port) + 
                  loc.pathname + "#somedivid";
Share:
28,925
tshauck
Author by

tshauck

Updated on October 11, 2020

Comments

  • tshauck
    tshauck over 3 years

    So I'm using jquerymobile for an app I'm creating. I have a link that if all the validation passes I'd like to go through, but if something fails I'd like to redirect.

    In the jquery something like this. Since it is jquerymobile the link will be a new div on the same index.html page - if that helps.

    $(#link).click(function(){  
      if(validation_fails) link_elsewhere;  
      else return true;
    }