How to insert dynamic URL parameters in HTML (Javascript) - javascript

I'm working on a marketing landing page that would take parameters in a URL and then display them in the HTML of an id on the page. Right now, I have every text placeholder defined in addition to each parameter from the URL.
The code below is working fine, but is there a way to remove the redundancies so that if any id matches the name of a parameter in the URL (e.g. a span has id "city" is automatically matched with the parameter "city"), they recognize and update the inner HTML? Thanks for any help.
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
const company_text = document.getElementById("company");
const company = urlParams.get('company');
if (company != null){
company_text.innerHTML = company;
}
const city_text = document.getElementById("city");
const city = urlParams.get('city');
if (city != null){
city_text.innerHTML = city;
}
Edited to update parameter names for clarity

You could put something like this at the end of your page
for(const [id, val] of urlParams.entries()) {
const htmlElement = document.getElementById(id);
if(htmlElement) {
htmlElement.innerHTML = val;
}
}
Keep in mind that the same parameter can appear more than one time in the query string (e.g. ?x=1&x=2). In that case there will be two entries with the same id.
Ref for entries.

This can be done by iterating over a list of all URL parameters and changing the HTML content of elements with the correct IDs.
var parameters = new URLSearchParams(window.location.search);
for (const parameter of parameters) {
document.querySelectorAll(`[id=${parameter[0]}]`).forEach(element => {
element.innerHTML = parameter[1];
});
}
I hope this solves your problem.
Best Regards,

Related

Getting out a product ID from URL - JavaScript

I'm trying to catch only a product ID from a URL. The ID is broke into 2 pieces:
https://www.example.org/category/first_part_of_ID-some_text-second_part_of_id
I was stuck with this function
var ft = "ft_";
var pod = "_";
var pageUrl = window.location.href;
var pageUrl1 = pageUrl.split("-")[1];
var pageUrl2 = pageUrl.replace("/","");
return pageUrl2;
}
Can anyone please help me clearing out everything except for the numbers? I tried with 2 different functions and putting it together, but it also didn't work.
This answer assumes the id you are trying to extract will always follow /category/ in the URL as well as that the first and second parts of the id always be located between the -some_text- part of the url
const url = window.location.href;
const urlAfterCategory = url.split('/')[4];
const id = `${urlAfterCategory.split('-')[0]}${urlAfterCategory.split('-')[2]}`
console.log(id); // Your id

HOW TO USE: Global Array in Function with Loop/While (JavaScript/GAS)

I would like to use a global array / variable in my function. The function should be executed as long as IDS are in the array.
In the variable "var files = [...];" there are for example two
IDS, depending on how many files are in the folder.
var files = ['16EdsAx', '16wQxxIc'];
var files = [];
function getListOfId(){
var folderId = "11tjb_odTJ2E_ez";
var filesN = DriveApp.getFolderById(folderId).getFiles();
while (filesN.hasNext()) files.push(filesN.next().getId());
//console.log(files);
}
Don't be intimidated, these two functions only read the DOCs documents
and write them into the corresponding cell.
function getDocItems(docID, identifier){
const body = DocumentApp.openById("13TlciLOZV").getBody(); // >>> The IDS from the array should be used here <<<<
const docText = body.getText();
//Check if search characters are to be included.
let startLen = identifier.start_include ? 0 : identifier.start.length;
let endLen = identifier.end_include ? 0 : identifier.end.length;
//Set up the reference loop
let textStart = 0;
let doc = docText;
let docList = [];
//Loop through text grab the identifier items. Start loop from last set of end identfiers.
while(textStart > -1){
let textStart = doc.indexOf(identifier.start);
if(textStart === -1){
break;
}else{
let textEnd = doc.indexOf(identifier.end) + identifier.end.length;
let word = doc.substring(textStart,textEnd);
doc = doc.substring(textEnd);
docList.push(word.substring(startLen,word.length - endLen));
};
};
//return a unique set of identifiers.
return [...new Set(docList)];
};
//The chewy conversation
function runsies(){
const docID = "13TlciLOZV"; // >>> The IDS from the array should be used here <<<<
const identifier = {
start: `ISIN: `,
start_include: false,
end: `VERRECHNUNGSKONTO`,
end_include: false
};
let results = getDocItems(docID, identifier);
//var commaAdd = results.join("''");
//console.log(results);
const ss = "17a55HCwlO5uF8gkXpG";//The spreadsheet ID
const sheet = "Stock_Data";//The sheet tab name
var activeSheet = SpreadsheetApp.getActiveSheet();
let importToSpredsheet = SpreadsheetApp.openById(ss).getSheetByName(sheet);
const range = activeSheet.getRange(6,1,results.length,1);
range.setValue(results);
};
Here you can find the tutorial where I got this code from. HERE
I always used the exact docs id in the code. But now I would like to use the ids from the array from the getListOfId () function. The information from the files should all be in different cells, ideally all in column A one below the other.
So my questions are:
How can I refer to the IDS in the other two functions?
The function should be repeated until all IDS have been used and all files have been read out and entered in the spreadsheet, but how?
I believe your goal as follows.
You want to retrieve the Google Document IDs from the function of getListOfId.
In this case, the IDs returned from getListOfId are always the file IDs of Google Document.
You want to use the file IDs to docID of let results = getDocItems(docID, identifier); in the function of runsies.
You want to put the values retrieved from the function of getDocItems to the sheet of Stock_Data in the Google Spreadsheet.
Modification points:
In this case, I would like to propose the following flow.
Retrieve the file IDs from getListOfId.
In this modification, the file IDs retrieved from getListOfId are used in runsies.
Put the file IDs to getDocItems using a loop.
Put the result values to the Spreadsheet.
When I saw your script for putting values to the Spreadsheet, the values are put to the active sheet. If you want to put the values to the sheet of Stock_Data in the Google Spreadsheet of const ss = "17a55HCwlO5uF8gkXpG";, it is required to modify the script.
And also, in your script, by const range = activeSheet.getRange(6,1,results.length,1); and range.setValue(results);, the 1st element in the array of results is put the number of times of the length of results from the cell "A6". When you want to put the values from the row 6, it is required to modify the script.
When above points are reflected to your script, it becomes as follows.
Modified script:
getListOfId()
Please set your folder ID.
function getListOfId(){
var folderId = "###"; // Please set your folder ID.
var filesN = DriveApp.getFolderById(folderId).getFiles();
var files = [];
while (filesN.hasNext()) files.push(filesN.next().getId());
return files;
}
runsies()
Please set your Spreadsheet ID.
function runsies(){
const docIDs = getListOfId(); // Here, the file IDs are retrieved from `getListOfId`.
const identifier = {
start: `ISIN: `,
start_include: false,
end: `VERRECHNUNGSKONTO`,
end_include: false
};
if (docIDs.length == 0) return;
const results = docIDs.map(id => getDocItems(id, identifier)); // Here, the retrieved file IDs are used in a loop.
const ss = "###"; // Please set your Spreadsheet ID.
const sheetName = "Stock_Data"; //The sheet tab name
const sheet = SpreadsheetApp.openById(ss).getSheetByName(sheetName);
const range = sheet.getRange(sheet.getRange(6,1).isBlank() ? 6 : sheet.getLastRow() + 1,1,results.length,results[0].length);
range.setValues(results);
}
In this case, when docIDs has not file IDs, the script is stopped.
In this modified script, from your script, the retrieved values results are put from the row 6 on the sheet of Stock_Data in the Google Spreadsheet const ss = "###". When the values has already been existing from the row 6, the values are appended.
getDocItems(docID, identifier)
From:
const body = DocumentApp.openById("13TlciLOZV").getBody();
To
const body = DocumentApp.openById(docID).getBody();
Note:
Please use this modified script with enabling V8 runtime.
If above modification is not the result you expect, can you show the whole script and the detail of your goal? By this, I would like to confirm it.
References:
map()
setValues(values)

Page refresh displays entire localstorage object

I have built a todo list using Vanilla Javascript and localstorage. The todo list has the following key, value:
key: todolist
value: [[\"id:0\",\"title:buy groceries\",\"done:false\"],
[\"id:1\",\"title:pick up dry cleaning\",\"done:false\"],
[\"id:2\",\"title:walk dog\",\"done:false\"]]
The values display just great on my website (only the title is displaying) but when I refresh the page, the whole object is displaying.
Before page refresh:
buy groceries
pick up dry cleaning
walk dog
After page refresh:
id:0,title:buy groceries,done:false
id:1,title:pick up dry cleaning,done:false
id:2,title:walk dog,done:false
Obviously, after a page refresh I only want the title to display on the list inside the li tag. It's a head scratcher because it only does this after a page refresh.
How do I get only the title to display after page refresh?
I'm somewhat of a newbie to Javascript and can't quite figure out how to make this happen. I've been Googling for almost two days and ready to tear my hair out!!
// set up some variables for elements on the page
const form = document.querySelector('form');
const ul = document.querySelector('ul');
const button = document.querySelector('button');
const input = document.getElementById('item');
// Fix empty array when script runs by making a conditional statement that
checks if localStorage already exists
//let itemsArray = localStorage.getItem('todolist') ?
JSON.parse(localStorage.getItem('todolist')) : [];
let todolist;
if (localStorage.getItem('todolist')) {
itemsArray = JSON.parse(localStorage.getItem('todolist'));
} else {
itemsArray = [];
}
localStorage.setItem('todolist', JSON.stringify(itemsArray));
const data = JSON.parse(localStorage.getItem('todolist'));
//alert(typeof(data));
// function that creates an li element, sets the text of the element to the
parameter, and appends the list item to the ul.
const liMaker = (text) => {
const li = document.createElement('li');
li.textContent = text;
ul.appendChild(li);
// Create a "close" button and append it to each list item
var span = document.createElement("SPAN");
var txt = document.createTextNode("🗑️");
span.className = "close";
span.appendChild(txt);
li.appendChild(span);
for (i = 0; i < close.length; i++) {
close[i].onclick = function() {
var div = this.parentElement;
div.style.display = "none";
}
}
}
// Event listener that submits the value of the input
form.addEventListener('submit', function (e) {
e.preventDefault();
var id = "id:" + itemsArray.length;
var title = "title:" + input.value;
var done = "done:" + "false";
itemsArray.push([id, title, done]);
//itemsArray.push(input.value);
localStorage.setItem('todolist', JSON.stringify(itemsArray));
liMaker(input.value);
input.value = "";
});
data.forEach(item => {
liMaker(item);
});
// clear items from todolist
button.addEventListener('click', function () {
localStorage.removeItem("todolist");
while (ul.firstChild) {
ul.removeChild(ul.firstChild);
}
itemsArray = [];
});
One thing I should note, the page refresh issue doesn't happen when I change the following:
itemsArray.push([id, title, done]);
to the following:
itemsArray.push(input.value);
The main reason you are having this problem is because your JSON is not formatted properly.
The reason you are only seeing the problem on page refresh is because at this point local storage contains the "todolist" key with your improperly formed JSON. This JSON value is then stored in your data variable and output to your list items in an undesired way (as you described).
Otherwise (without page refresh) the text of your list items is coming directly from the text in the input field.
If you make the following changes to your code it will work properly (I have tested it). Hope it helps.
JavaScript comments
Firstly i'm not sure if this just happened when you posted your code here but if your comments in JS extend across two lines or more then you need to put // on all lines.
For example in your code you have:
//function that creates an li element, sets the text of the element to the
parameter, and appends the list item to the ul.
and it should be:
//function that creates an li element, sets the text of the element to the
//parameter, and appends the list item to the ul.
The format of your JSON
Secondly I see a problem with the way the JSON is formatted.
It should look something like the following (before slashes are added).
[{"id":0,"title":"buy groceries","done":false},
{"id":1,"title":"pick up dry cleaning","done":false},
{"id":2,"title":"walk dog","done":false}]
Note each property name (i.e "id", "title" and "done") should have double quotes and each property value (e.g "buy groceries") should have double quotes (unless its an int or a boolean etc).
You can use a tool called JSLint to check your JSON is valid.
So in order to create your JSON in the right format (when the form is submitted)
change these lines of code:
var id = "id:" + itemsArray.length;
var title = "title:" + input.value;
var done = "done:" + "false";
itemsArray.push([id, title, done]);
to the following:
var idValue = itemsArray.length;
var titleValue = input.value;
var doneValue = false;
itemsArray.push({"id": idValue, "title": titleValue, "done" : doneValue});
Iterating through the array
Your data variable will contain the array of todolist objects (from local storage).
So therefore the item you have in the following code will contain the full object i.e {"id":0,"title":"buy groceries","done":false}.
So in order to get the title here you need to say item.title. (This will work now that the JSON will be properly formatted):
data.forEach(item => {
//log the item to check it.
console.log(item);
liMaker(item.title);
});

Javascript input id value to url

I would appreciate any help to build a basic javascript that would extract the forum input name value and create a new URL from the value that is extracted, and repeat with the new URL until the value that extracted is -1. That would be the final URL. Once found the final url will be opened.
For example if the source code states that
<input name="nextPage" ... value="10908071">
The script would extract the nextPage value which is 10908071 and input it into the url thus forwarding to www.url.com/xyz?page=10908071
When the next url is identified the script will loop and extract the nextPage value once again until the value is -1.
Once the value is -1 the final web url will be found and preferably opened.
Any help is greatly appreciated.
p.s. this is my first post, I would always find my answer here without the need to post but this seems a bit more complicated.
Just use a loop and make network requests until you get to the desired value:
async function findURL() {
let value;
const baseURL = window.location.href; // I assume this is eg 'www.url.com/xyz'
let pageURL = baseURL;
while (value !== '-1') {
const response = await fetch(pageURL);
const responseText = await response.text();
const responseDocument = (new DOMParser()).parseFromString(responseText, 'text/html');
value = responseDocument.querySelector('input[name="nextPage"]').value;
if (value !== '-1') pageURL = baseURL + '?page=' + value;
}
// final URL found, redirect to its page:
window.location.href = pageURL;
}
But you'll have to be pretty certain that the value eventually ends up being -1.

Display the results of an array on another page

I'm trying to load an array from one page and then have the results appear on another using javascript/jQuery. So a user will make a selection from a dropdown. Based on this dropdown the "customers" address, phone, email, etc. will appear in a text field. I'm trying to store those results in to the array (name | address | etc in one index of the array), display the result on the second screen, and then allow the user to add more names if necessary.
At the moment I'm trying to use localStorage to store the values and then JSON.stringify to convert the results so they can be stored in the array.
I think these are all of the pertinent lines:
var customerArray = [];
var getName = $('#DropDownList1').val();
var getAddress = $('#DataList1').text().trim();
var getPhone = $('#DataList2').text().trim();
var getEmail = $('#DataList3').text().trim();
//store the variables
localStorage.setItem("name", getName);
localStorage.setItem("address", getAddress);
localStorage.setItem("phone", getPhone);
localStorage.setItem("email", getEmail);
//user will click #btnAdd to add the customers information
//into customerArray[]
$("#btnAdd").click(function () {
var setName = localStorage.getItem("name");
var setAddress = localStorage.getItem("address");
var setPhone = localStorage.getItem("phone");
var setEmail = localStorage.getItem("email");
var post = setName + setAddress + setPhone + setEmail;
if (customerArray.length == 0) {
customerArray[0] = post;
} else {
for (var i = 1; i < customerArray.length; ++i) {
//store results of 'post' into the array
customerArray.push(post);
localStorage.setItem("storedArray",JSON.stringify(customerArray));
}
}
}); //end #btnAdd click event
Form here the 2nd page will load with a text field that will (should) display the results of the array (customerArray). Unfortunately I can only get 1 value to appear.
At the moment this is the block being used to display the results:
$('#tbContactList').val(JSON.parse(localStorage.getItem("storedArray")));
If it matters I'm writing the application using Visual Studio Express 2012 for Web. The data that initially populates the customers information comes from a database that I've used ASP controls to get. I'm confident there is a perfectly simple solution using ASP/C# but I'm trying to solve this problem using javascript/jQuery - I'm more familiar with those languages than I am with C#.
Thank you.
Use Array.join() to turn your array into a string to store.
Then use Array.split() to turn your string back into an Array.
Example
var arr=['name','email','other'];
var localStorageString=arr.join(',');
localStorage.setItem('info',localStorageString);
var reassemble=localStorage.info.split(',');
for(var i=0;i<reassemble.length;i++){
document.body.innerHTML+=reassemble[i]+"<br/>";
}
http://jsfiddle.net/s5onLxd3/
Why does the user have to leave the current page though? IS a tabbed/dynamic interface not an option?

Categories

Resources