Javascript input id value to url - javascript

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.

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 insert dynamic URL parameters in HTML (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,

JavaScript: How to get first parameter, actually first key from URL?

I am trying to get first key from URL, like this:
const currentUrl = window.location.href;
const parmsFromUrl = new URLSearchParams(currentUrl);
const paramToCheck = parmsFromUrl.keys[0];
But constantly I get undefined, can someone tell how me how to get only first parameter, not a value, I just want key? Thanks.
With URLSearchParams you have to use window.location.search
With URL you have to use window.location.href
const currentUrl = window.location.search;
const parmsFromUrl = new URLSearchParams(currentUrl);
URLSearchParams.keys() returns an iterator, so you have to use next() to get first value
const paramToCheck = parmsFromUrl.keys().next().value;

ASP MVC JavaScript ActionLink multiple replace?

I want to build a Url.Action link and pass parameters and I found an example here on stackoverflow that shows how to replace the value:
var url = "#Url.Action("Export", "UserCalendar",new { from =
"_date", to="_to", groupId="_groupId" })".replace("_date",
_pdfExportStartDate);
How do I also replace _to and _groupId ? I tried
url = url.replace("_to",_pdfExportEndDate)
after the first replace call and although it makes the correct URL string the value (_to) is never passed to the controller.
You can simply add the querystring params to the base url (the one without any route values) as needed.
var _pdfExportStartDate = "11/11/2013";
var _toDate = "11/11/2013";
var baseUrl = "#Url.Action("Export", "UserCalendar")";
url = baseUrl +"?from = "+_pdfExportStartDate +"&to= "+ _toDate;

HTML5 Local Storage item not being saved correclty

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.

Categories

Resources