Javascript redirect and Pass Argument to redirected Page
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.
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, 2022Comments
-
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 over 12 yearsdoes 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 over 12 yearsAs long as
page.html
exists it will work, there's no server-side operation involved -
Saher Ahwal over 12 yearsOne more thing, I have the buttons already made as <a href> links, is that still possible?
-
Clive over 12 yearsNot 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 over 12 yearsHow 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 over 12 yearsYou'll need a function to extract the URL parameters, there's one here