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 use javascript to get a list of params pretty easily with the following line.
var paramArray = window.location.search.substring(1).split("&")
This will build an array of the parameters of the query string. From there you just need to add logic to find the param you specified in your question and take the appropriate redirect using
window.location.href = 'some URL'; //causes the browser to refresh with the new URL
Example:
function getQueryStringArray(){
var assoc=[];
var items = window.location.search.substring(1).split('&');
for(var j = 0; j < items.length; j++) {
var a = items[j].split('='); assoc[a[0]] = a[1];
}
return assoc;
}
//point at which you want to determine redirection
var qs = getQueryStringArray();
var url = '';
if (qs.lang !== 'undefined' && qs.lang) {
switch (qs.lang) {
case 'en':
url = 'blah';
break;
case 'de':
url = 'meh';
break;
}
window.location.href = url; //reroute
}
See this on how to parse query string parameters using jQuery How can I get query string values in JavaScript?
Then you can redirect to another page with window.location
Something like this
<script>
$(document).ready(function(){
var p = getParameterByName("lang");
var rootUrl = "yourRootUrl";
var url = rootUrl + p + '/default.htm';
window.location = url;
});
</script>
No jQuery
<script>
(function(){
var p = getParameterByName("lang");
var rootUrl = "yourRootUrl/";
var url = rootUrl + p + '/default.htm';
window.location = url;
}());
</script>