I'm trying to save a value from a url query string that needs to be inserted into forms an any page the user navigates to, but so far I can't get the code to work past the initial landing page that contains the original query string.
Using this method to grab the query string value for X, and save it in localStorage for key Xcode:
<script>
var field = 'x';
var url = window.location.href;
if(url.indexOf('?' + field + '=') != -1) {
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
var user_code = getUrlVars()["x"];
if (localStorage) {
localStorage.setItem("xcode",user_code);
}
</script>
Then use this to insert it into the "value" attribute of any inputs withe class .xcode-field:
<script>
window.onload = function() {
var thecode = localStorage.getItem("xcode");
if (thecode != "undefined" && thecode != "null") {
$(".xcode-field").attr("value",thecode);
} else {
$(".xcode-field").attr("value","default");
}
}
</script>
If the item is not in LocalStorage, the default value should be inserted (or it should just do nothing, but not sure how to set that.)
My problem now is that this works on the page the user lands ( example.com/?x=1234 ) but when they navigate to any other pages, the value in the form is populated by "undefined". So neither is the query string value being properly stored nor does the else statement above work to insert "default". Any idea what I'm doing wrong here? Thank you!
Fiddle (but does not seem to work on there): http://jsfiddle.net/08suhbuk/
UPDATE: Finally figured it out! The LocalStorage was being reset on consecutive pages because the initial query string parsing and setItem would be repeated on every page and override the original value. I solved it by adding the following code to check for the presence of a query string around the first script:
var field = 'x';
var url = window.location.href;
if(url.indexOf('?' + field + '=') != -1) {
Final working code edited in.
Related
On my shop i have a filter. When a filter is selected it adds "filter.p.tag=xxx" parameter to the url. Since i have no other possibility to display current active filters, i need to grab them from the URL. And output them under the h1 and update in realtime when a new filter is selected.
For example the URL:
collections/all?filter.p.tag=animal&filter.p.tag=glitter&fbclid=2123¶mblabla=123123
-actually i only want everything after (filter.p.tag) - so in this example under the H1 Heading there should be following:
"Animal & Glitter"
I want to ignore every other parameter without "jquery remove or replace" them since this is unwanted.
THE QUESTION IS: How am i able to only consider the filter.p.tag param and ignore all others?
Now i have this code:
<script>
// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
function removeDuplicates(arr) {
return arr.filter((item,
index) => arr.indexOf(item) === index);
}
jQuery( document ).ready(function( $ ) {
jQuery(document.body).on('click', ".label_filter", function(){
setTimeout(function(){
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[1]);
// vars[hash[0]] = hash[1];
}
var unqvars = removeDuplicates(vars);
var result = '';
for(var i = 1; i <= unqvars.length; i++){
if(i == unqvars.length){
var sept = '';
}else{
var sept = ' & ';
}
result = unqvars+ sept;
}
var replaced = result.replaceAll(',', ' & ');
var replaced1 = replaced.replaceAll('+', ' ');
var replaced2 = replaced1.replaceAll('-', ' ');
var replaced3 = replaced2.replaceAll('& Page=', ' Seite ');
jQuery('#categoryfromfilter').text(replaced3);
}, 1000);
});
});
</script>
```
Less code, more robust
URLSearchParams().getAll() works well when there are multiple values for the same key name.
However, additional code is needed to make the function handle a wide range of input. For example, here we first parse the query string from the url. URLSearchParams would fail if the path were passed, e.g., /somepath?key=value. Query string values might also be encoded and so decodeURIComponent() is applied to each value.
const getParam = (url, key) =>
new URLSearchParams(url?.toString().split("?").pop())
.getAll(key).map(value => decodeURIComponent(value));
Example:
let url = "/collections/all?filter.p.tag=animals&filter.p.tag=glitter",
key = "filter.p.tag",
result = getParam(url, key);
// Output: "animals,glitter"
Update
OP asked for additional code to pull the filter values from window.location.href. We can use this href to create a URL and then modify the original solution to use URL.searchParams.
Additionally, OP wants to retrieve the filters whenever the page query string changes. This most likely happens when the user clicks a filter option that causes the page to reload with new data. For this we can use the DOMContentLoaded event to check for new filters when the page loads. While less likely, the page might also use History.pushState() to update the query string and for that we could use the popstate event.
function onQueryChange() {
let key = "filter.p.tag";
let url = new URL(window.location.href);
let filters = url.searchParams.getAll(key)
.map(value => decodeURIComponent(value))
.join("&");
// do something with the filters...
}
document.addEventListener("DOMContentLoaded", onQueryChange);
// document.addEventListener("popstate", onQueryChange);
Snippet
Code snippet that displays a range of test values.
const getParam = (url, key) =>
new URLSearchParams(url?.toString().split("?").pop())
.getAll(key).map(value => decodeURIComponent(value));
// Test Values
let name = "filter.p.tag";
["/collections/all?filter.p.tag=animals",
"/collections/all?filter.p.tag=animals&filter.p.tag=glitter",
"/collections/all?fbclid=IwAR2didTPblablabla&filter.p.tag=animals",
"/collections/all?filter.p.tag=animals&fbclid=IwAR2didTPblablabla&filter.p.tag=glitter",
"/collections/all?sort_by=apes&filter.p.tag=animals&fbclid=IwAR2didTPblablabla",
"fbclid=IwAR2didTPblablabla&filter.p.tag=animals",
"filter.p.tag=animals&filter.p.tag=glitter&fbclid=IwAR2didTPblablabla",
"/collections/all?fbclid=IwAR2didTPblablabla",
"filter.p.tag&fbclid=IwAR2didTPblablabla",
"/collections/all",
null,
undefined
].forEach(url => stdout.innerHTML += (`Returns "${getParam(url, name)}" for "${url}"\n`));
<xmp id="stdout"></xmp>
I've recently switched my site to use clean/SEO-friendly URLs which has now caused me some issues with a JavaScript function I had for grabbing the query string parameters.
Previously I had been using this function:
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
return (false);
}
Which worked fine on things like this as you could just call getQueryVariable("image") and return "awesome.jpg".
I've been playing with the indexOf(); function to try and grab the relevant parameters from the current URL, eg:
var url = window.location.pathname;
var isPage = url.indexOf("page") + 1;
In an attempt to get the array index number of the "page" parameter, and then plus 1 it to move along to the value of that (?page=name > /page/name/)
JavaScript isn't my main language, so I'm not used to working with arrays etc and my attempt to turn this into a new function has been giving me headaches.
Any pointers?
How about something like this? It splits the path and keeps shifting off the first element of the array as it determines key/value pairs.
function getPathVariable(variable) {
var path = location.pathname;
// just for the demo, lets pretend the path is this...
path = '/images/awesome.jpg/page/about';
// ^-- take this line out for your own version.
var parts = path.substr(1).split('/'), value;
while(parts.length) {
if (parts.shift() === variable) value = parts.shift();
else parts.shift();
}
return value;
}
console.log(getPathVariable('page'));
This can be done formally using a library such as router.js, but I would go for simple string manipulation:
const parts = '/users/bob'.split('/')
const name = parts[parts.length - 1] // 'bob'
I've got a bit of javascript (shown below in a simplified format) which is the "ad tag" from the ad server that brings up an ad unit on the html page.
<script type="text/javascript" src="http://adserverdomain.net;pcode=1234;city=nameofcity;suburb=nameofsuburb"></script>
The javascript has more variable but I've just shown one.
Below this I have a <div> in which I'd like to pull the variable "pcode" from the above javascript and display it's value using
$('div').html("");
So the <div> needs to be populated with the value "1234".
Any idea how I can do this? Thanks
EDIT: I've updated the url (added .net and some other variables after pcode to avoid confusion). Also, I don't have access to the initial script, so I can't add an id to it. The script is generated by the ad server and it always has the variable pcode (with a different value). just need to be able to display that in another div on the same html page.
Try
<script type="text/javascript" src="http://adserverdomain;pcode=1234;city=sajdhsk;suburb=asdsadas"></script>
<div id="pcode"></div>
<div id="city"></div>
<div id="suburb"></div>
then
var pcodesrc = $('script[src^="http://adserverdomain;"]').attr('src');
$('#pcode').html(pcodesrc.match(/pcode=(.+?)(?=(;|$))/)[1])
$('#city').html(pcodesrc.match(/city=(.+?)(?=(;|$))/)[1])
$('#suburb').html(pcodesrc.match(/suburb=(.+?)(?=(;|$))/)[1])
Demo: Fiddle
or
$('#pcode').html(pcodesrc.match(/pcode=([^;]+)/)[1])
$('#city').html(pcodesrc.match(/city=([^;]+)/)[1])
$('#suburb').html(pcodesrc.match(/suburb=([^;]+)/)[1])
Demo: Fiddle
Try this with url.Actually the below code get data from url querystring.Edit it and give your url.
function getUrlVars() {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
var me = getUrlVars()["pcode"];
Try this buddy
function getvalues()
{
var values = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) { values[key] = value;});
return values;
}
whenever you want to use it
var value = getvalues()["pcode"];
Use this value to put in your html element
This is third time and i want to make it clear for my problem. So in the first page i display my whole record that i saved in database, and when i want to view the selected details at second page, i need to click the selected data and view, but nothing happen and i have no idea how to link the VIEW to second page that can show all the data, i had capture down the pictures so that hope you all can help me, big thanks.
This is First page
This is the second page that i want to show the detail in the text field
The coding is like this (first page::to show the whole records and link to second page)
function showRecords(){
results.innerHTML='';
db.transaction(function(tx)
{
tx.executeSql(selectAll,[],function(tx,result)
{
dataset = result.rows;
for(var i=0,item=null;i<dataset.length;i++)
{
item = dataset.item(i);
results.innerHTML+=
'<li>' + item['fname'] + ' view'+'delete'+'</li>';
}
});
});
}
function loadRecord(i){
var item=dataset.item(i);
fname.value = item['fname'];
id.value = item['id'];
window.location.href="userup2.html?loadRecord("+i+")";
return false;
}
Please give me some idea and example, im using web sql to store data, i already ask this question for few times and im newbie for the html and javascript, please help me and this is important.
Yes you can achieve it using query strings. As I am not aware of web-sql, I will show you how to add query string to url in first page and how to retrieve it in second page.
JS CODE:
function loadRecord(i){
var item=dataset.item(i);
fname.value = item['fname'];
id.value = item['id'];
window.location.href="userup2.html?id="+i;
return false;
}
In the above function we are adding i (id of one record) as query string.
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
This code will help you to get the query string from url.
Example:
var id = getUrlVars()["id"];
The above line will help you to get id that you passed in first page and you may use it to retireve the details from database.
Hope this helps you :)
Im trying to pull a specific file name from a URL, Ive looked at the posts but there isnt anything that answers the question that I need. I need a Javascript or Jquery that can pull just the file name ("Test1") from:
http://sharepoint/sites/Jarrod/DurangoTest/SitePages/Home.aspx?RootFolder=%2Fsites%2FJarrod%2FDurangoTest%2FShared%20Documents%2FTest1&FolderCTID=0x01200094D5A58A4F099E49BE1A8BA2F7DE9E0D&View={653454F3-1CE4-48C1-967C-5BA6023D349E}
You can get url information like that from the window.location object. Try this out
params = window.location.search.split(/&/)
for (var i=0; i < params.length; i++) {
if (params[i].match(/^\??RootFolder=/)){
paths = params[i].split(/\//);
filename = paths[paths.length-1];
break;
}
};
#Jonathan is on the right track. It looks like you're looking to parse a value from the querystring rather than find the name of the requested file. You'll first need to get the value from the querystring. You can use window.location.search to get the full querystring from the URL. Then parse the querystring to find the value you want. Here's a little JS function that does that:
// parses the query string provided and returns the value
function GetQueryVariable(query, name) {
if (query.indexOf("?") == 0) { query = query.substr(1); }
var pairs = query.split("&");
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split("=");
if (pair[0] == name) {
return pair[1];
}
}
return "";
}
Then you're ready to parse the value using Jonathan's suggestion to get the name of the file. You might have to do some unescaping (using the JS method unescape) to convert the value from the querystring into the "real" value that can be parsed more easily.