How to redirect a page using JQuery

If you want to redirect from one page to another page when clicking on a button or any other element using JQuery you can do it in the following ways.

You can use

1. window.location.replace("url") or

2. window.location.href = "url"; or

3. $(location).attr('href', url);

Consider you have a button, and when you click on that button, you have to redirect to another page. For this we csn use the below code

<input type="button" id="redirect" value="click to redirect" />

The JQuery code is

1. Using window.location.replace

$(document).ready(function () {
    $("#redirect").click(function () {
    window.location.replace("http://google.com"); //page will redirect to google.com   
 })

2. Using window.location.href

$(document).ready(function () {
      $("#redirect").click(function () {
          window.location.href ="http://google.com";
      })
})

3. Using $(location).attr

 $(document).ready(function () {
        $("#redirect").click(function () {
           var url = "http://google.com"
           $(location).attr('href', url);
         })          
  })

It is better to use window.location.replace than using window.location.href, because replace() does not put the originating page in the session history, meaning the user won't get stuck in a never-ending back-button fiasco. If you want to simulate someone clicking on a link, use location.href. If you want to simulate an HTTP redirect, use location.replace.

In this way you can redirect from one page to another page using JQuery

Hope it helps you.

read our previous post : Check Given Date Greater than Current Date JavaScript/JQuery

For more posts on JQuery see here : JQuery

No comments:

Post a Comment