37

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;
}
1
  • this truely is just javascript, nothing really going on with jquery. Commented Jan 6, 2011 at 3:45

4 Answers 4

17

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

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

Sign up to request clarification or add additional context in comments.

Comments

13

You can use JavaScript's native window.location

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

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

Comments

2

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;
}

Comments

1
$(#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";

1 Comment

loc.port can be used when port number needed

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.