Javascript redirect and Pass Argument to redirected Page

12,858

Solution 1

Cross-browser event handling is much simpler with a toolkit like JQuery:

HTML:

<button data-param="foo">Foo</button>
<button data-param="bar">Bar</button>

JQuery code:

$('button').click(function(){
    window.location = window.location.href + '?param=' + $(this).data('param');
});

Demo: http://jsfiddle.net/6DK5J/

Solution 2

It depends what you mean by 'pass in an argument' but if you mean by URL query string then you can simply set up a form with an action to the page in question with a GET method:

<form action="page.html" method="GET">
  <input type="submit" name="submit1" value="Submit1" />
  <input type="submit" name="submit2" value="Submit2" />
</form>

The redirected URL will be page.html?submit1=Submit1 if the first button is clicked and page.html?submit2=Submit2 if the second button is clicked.

Share:
12,858
Saher Ahwal
Author by

Saher Ahwal

Software Engineer at Microsoft LinkedIn Profile MEng Thesis: Optimizations to a massively parallel database and support of a shared scan architecture

Updated on June 04, 2022

Comments

  • Saher Ahwal
    Saher Ahwal almost 2 years

    I have a main page that contains two buttons. Each of the buttons should redirect to the same page, however, the page that you are redirected to should do different things depending on the button you pressed. How can I redirect the user to that new page and pass in an argument depending on which button you have clicked?

  • Saher Ahwal
    Saher Ahwal over 12 years
    does the GET here work even when you are offline, i.e the page should be purely javascript and should work offline ? and can you add how in javascript I can pick up the querystring please.? THANKS
  • Clive
    Clive over 12 years
    As long as page.html exists it will work, there's no server-side operation involved
  • Saher Ahwal
    Saher Ahwal over 12 years
    One more thing, I have the buttons already made as <a href> links, is that still possible?
  • Clive
    Clive over 12 years
    Not using that method, no, only values from <input> elements would be included in the query string. Are you able to change the links to <input> elements?
  • Saher Ahwal
    Saher Ahwal over 12 years
    How can I then pick it up at the javascript that is that connects to the second page I am redirecting to ? say I an in page.html?p=1 , what is the function that I can use to get p? is it this.data ?
  • Clive
    Clive over 12 years
    You'll need a function to extract the URL parameters, there's one here