On the Details page, use the URL object to get access to the url params, for example:
const url = new URL(window.location.href);
console.log(url.searchParams.get("id"));
Answer from Petr Broz on Stack OverflowRedirect to url with hidden parameters - JavaScript - SitePoint Forums | Web Development & Design Community
javascript - How to 3xx redirect and pass a value from a table as a query parameter (in the URL)? - Stack Overflow
javascript - Redirect to page and pass text and image parameter - HTML JS - Stack Overflow
Get url params and redirect to url after
On the Details page, use the URL object to get access to the url params, for example:
const url = new URL(window.location.href);
console.log(url.searchParams.get("id"));
You can get the parameters from the url in your details page with the following code:
var url = new URL(window.location);
var param = url.searchParams.get("parameterName");
As @Michael Hurley points out, url is not available in some browsers (namely IE), so if you need to support them you'll have to do some additional work:
exp = /(?:parameterName=)(\w)/
match = str.match(exp)
//match[1] would hold the value of 'parameterName'
Set the user name as data-username attribute to the button and also a class:
HTML
<input type="button" name="theButton" value="Detail" class="btn" data-username="{{result['username']}}" />
JS
$(document).on('click', '.btn', function() {
var name = $(this).data('username');
if (name != undefined && name != null) {
window.location = '/player_detail?username=' + name;
}
});โ
EDIT:
Also, you can simply check for undefined && null using:
$(document).on('click', '.btn', function() {
var name = $(this).data('username');
if (name) {
window.location = '/player_detail?username=' + name;
}
});โ
As, mentioned in this answer
if (name) {
}
will evaluate to true if value is not:
- null
- undefined
- NaN
- empty string ("")
- 0
- false
The above list represents all possible falsy values in ECMA/Javascript.
Do this :
<script type="text/javascript">
function showDetails(username)
{
window.location = '/player_detail?username='+username;
}
</script>
<input type="button" name="theButton" value="Detail" onclick="showDetails('username');">
To pass both parameters, you may try this
jQuery(document).ready(function($){
$('.product').click(function(event) {
event.preventDefault();
var name = $(this).data('title'), img = $(this).data('img')
window.location = './lineup/index.html?title=' + name + '&img=' + img;
});
});
To parse a value by key from url you can use this function (Source : MDN)
function loadPageVar (sVar) {
return decodeURI(window.location.search.replace(new RegExp("^(?:.*[&\\?]" + encodeURI(sVar).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1"));
}
In your lineup/index.html put this code and the function given above
$(function(){
$('#title-area').text(loadPageVar('title'));
$('.product-img').text(loadPageVar('img')); // will set text
// To set an image with the src
$('.product-img').append($('<img/>', {
'src':loadPageVar('img')
}));
});
If you're looking for an alternative to URL query strings I'd look into window.sessionStorage object.
Store parameters like so:
$('.product').click(function(event) {
event.preventDefault();
window.sessionStorage.setItem('name', $(this).data('title'));
window.sessionStorage.setItem('imgSrc', $(this).data('img'));
window.location.reload(); //refreshes the page
});
Then to load the attributes, should they exist, add the following:
$(function(){
if (window.sessionStorage.length){
$('#title-area').text(window.sessionStorage.getItem('title'));
$('.product-img').append($('<img/>', {
'src':window.sessionStorage.getItem('imgSrc')
}));
}
//include the click event listener for .product link here too
});
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/
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.
The following will get the current URL querystring:
var query = window.location.search;
That can then be used in the redirect:
window.location.replace('sample.com' + query);
DOCS
Update
The .replace() method will remove the current URL from the browser history. If you want to retain the current URL use .assign() as mentioned by @igor
Modify the location object:
location.href = location.href.replace ( new RegExp("^" + "http://test.com"), "http://sample.com/" );
The statement replaces the start of the url from which the current document has been loaded. The resource from the new url will be loaded automatically.
Your sample urls do not contain path and fragment portions ( like in http://test.com/the/path/compon.ent?a=1&b=2#a_fragment). They are accessible as
location.pathname // 'http://test.com/the/path/compon.ent'
location.hash // '#a_fragment'
Note that the occurrence of these url components suggest to expressly compose the new url the way @MattSizzle outlines in his answer.
You can get the URL via JS very easily.
You have not provided the button click code in the question. So I am assuming there can be two ways to be redirected to another page;
You can add a button and write a click function to redirect;
<button onclick="redirect()"> Go To Page 2 </button> <script> function redirect() { var currentUrl = window.location.href; var parts = currentUrl.split("/"); var param = parts[parts.length() - 1]; window.location.hef = page2_url + "/" + param; } </script>You can also add an anchor tag for redirection;
<a href="page2_url" id="redirectlink"> Button </a> <script> (function(){ var currentUrl = window.location.href; var parts = currentUrl.split("/"); var param = parts[parts.length() - 1]; $("#redirectlink").attr("href", "page2_url" + "/" + param) })() </script>
You can use window.location.href to get the current URL of the page you're on. This will be stored as a string. You can then use .split('/') to turn your string into an array of parameters (where each index is split based on a /).
Eg:
"page.com/page1/food".split('/')
will yield:
const params = ["page.com", "page1", "food"]
To get the last element of this array you can use params.length-1 as the index, and then append this retrieved value onto the end of your redirected page. To redirect you set window.location.href equal to the new url.
See working example below:
$('#redirect').click(function() {
const url = window.location.href; // 'https://stacksnippets.net/js'
const params = url.split('/'); // ['https', '', 'stacksnippets.net', 'js']
const parameter = params[params.length-1]; // 'js'
const page2 = "https://www.example.com/" +parameter; // 'https://www.example.com/js'
alert("Going to new page: " +page2);
window.location.href = page2 // Go to page2 url
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="redirect">Click me</button>