Passing variable when opening another html page using JavaScript - javascript

This is probably a really silly question, but I can't find it online anywhere and I've been looking for at least an hour.
I have a link Instruments which I want to get the ID of it once clicked, as I need to pass some variable to the page I am opening to know that the instruments link was clicked. This is being called from productInformation.html
I have also tried doing Instruments and then in my JavaScript, window.open("MusicMe.html", "_self"); and then tried passing a variable that way, but still absolutely no luck. Any help as to how I would pass a variable back to the page when it opens would be brilliant.
Once it opens, I am using the variable to set the ID of an element so it only displays a certain set of the information, which is working on it's own, but when I go back to try and call it, it's always thinking it is showing them all as I cannot work out how to set the variable to define it. Unfortunately I need to use JavaScript not PHP.
Thanks.

I would just tell you some ways, hope you would be able to implement it:
Use query params to pass the variable.
When you're navigating to another page, add query params to the url.
window.open("MusicMe.html?variable=value", "_self");
In your next page, check for queryParam by getting window.location.href and using regex to split the params after ? and get that data.
Use localStorage/cookies
Before navigating to the next page, set a variable in your localStorage
localStorage.setItem("variable","value");
window.open("MusicMe.html", "_self");
In your second page, in the window load event.
$(function() {
if(localStorage.getItem("variable")) {
// set the ID here
// after setting remember to remove it, if it's not required
localStorage.removeItem("variable");
}
});

You can use localStorage to keep the value, or use parameter like
href="MusicMe.html?id=111"
to pass the value to new page.

You can always pass a GET variable in you re URL just like this myhost.com?var=value
You can get the value of this variable by parsing the URL using Js see this
How can I get query string values in JavaScript?

You can simply pass # value into url, get it and then match it with 'rel' attribute given on specified element.
Here I have done materialize collapsible open from link on another page.
JS:
var locationHash = window.location.hash;
var hashSplit = locationHash.split('#');
var currentTab = hashSplit[1];
$('.collapsible > li').each(function() {
var allRels = $(this).attr('rel');
if(currentTab == allRels){
$(this).find('.collapsible-header').addClass('active');
$(this).attr('id',currentTab);
}
});

Related

Cookie based on page path

Is it possible to set a cookie value, as the url page path?
i.e I have a cookie that is set when someone clicks a button with the ID mybtn but I'd like the value of the cookie to be automatically generated based on the last part of the page path. For example if the user clicked the button whilst on a page www.myweb.com/cars/car1 the value of the cookie should be set as car1. The code below is where I've got to so far, but it's the "THEPAGEPATH" where I'm stuck as I guess I need to use javascript to pull the url information.
<script>$("#mybtn").bind("click", function() {
document.cookie="model=THEPAGEPATH;path=/;"
});</script>
Simple solution would be to just split the string, and take the last part of it.
<script>$("#mybtn").bind("click", function() {
const strings = window.location.href.split("/").filter(str => !!str)
document.cookie=`model=${strings[strings.length - 1]};path=/;`
});</script>
This works for both routes with and without trailing slash. It does not work for routes that have query parameters that contains slashes. If you need to support that, you could split the string on ?, and the use the same logic on the first part of the string.

Stuck in a conditional redirect loop

I want the application to change the url in the browser to set the parameters if the parameters do not match the item value on initial load of the page.
I tried to create a conditional check to see if the substring matched anywhere within the URL. However, I get caught in a loop. Something tells me my use of wildcards is incorrect.
htp.p('<script>
if(window.location.href !== "*'||:P4_TEAM||'*") {
window.location.href = "https://apextserverurl/ords/f?p=80001:4:::::P4_TEAM:'||:P4_TEAM||'"
}
</script>');
Since the page item cannot be null, the thought is on the initial load, it will push the parameters into the URL and adjust accordingly. The actual result shows the url parameters load into the browser correctly, but it seems to fail the logic test on the javascript and keeps refreshing instead
Your page refreshes endlessly, because your if condition will always be true (Because you can't use wildcards in JavaScript...at least not like that) and window.location.href will reload your page.
You could use a Regex, but for your example a simple string.includes() is sufficient.
You can just check with includes() like so:
// If ':P4_TEAM' is not in the url
if(!window.location.href.includes(':P4_TEAM')) {
// Set the url to the provided string (and refresh the page)
window.location.href = "https://apextserverurl/ords/f?p=80001:4:::::P4_TEAM:'||:P4_TEAM||'";
}

How to pass value to html input field which is opened through window.open() [duplicate]

I am trying to use window.open() to pass along some arguments to another page.
I want the page to be
myPage.html?img=1.jpg
Where once on that page I will use javascript to get the arg and show the image.
However I cannot figure out how to do this with window.open() cause it says the pages does not exist which I can understand.
window.open('myPage.html?img=1.jpg','_blank')
Hope this makes sense and I don't even know if it is possible.
myPage.html should exist,
and check the docs on window.open
to pass vars:
var variable = "lol";
var w = window.open("http://example.com");
w.variable = variable;
or yopu can visit the opeing window:
var variable = window.opener.variable;

HTML Append Variable to Query String

I have http://localhost/?val=1
When I click on a link, is there a way this link can append a query variable to the current string, for example:
Link
so when I click it the url would be:
http://localhost/?val=1&var2=2
but when I click the link it removes the first query string and looks like
http://localhost/&var2=2
Is such a thing possible with normal HTML?
You can't do that using only html, but you can do it with js or php:
Using JS:
<a onclick="window.location+=((window.location.href.indexOf('?')+1)?'':'?')+'&var2=2'">Link</a>
Using Php:
Link
Notice 1: make sure you don't have the new variable in the current link, or it'll be a loop of the same variable
Notice 2: this is not a professional way, but it could work if you need something fast.
Basically you want to get your current URL via JavaScript with:
var existingUrl = window.location.href; // http://localhost/?val=1
Then append any Query Strings that are applicable using:
window.location.href = existingUrl + '&var2=2';
or some other similar code. Take a look at this post about Query Parameters.
Note: A link would already have to exist with an OnClick event that calls a function with the above code in it for it to work appropriately.
Now obviously this isn't very useful information on it's own, so you are going to want to do some work either in JavaScript or in Server code (through use of NodeJS, PHP, or some other server-side language) to pass those variable names and their values down so that the button can do what you are wanting it to do.
You will have to have some logic to make sure the query parameters are put in the URL correctly though. I.E. if there is only one query param it's going to look like '?var1=1' and if it's any subsequent parameter it's going to look like '&var#=#'.

Convert location.href URL to Anchor link

Exists any JavaScript or Objective-C method to convert a location.href="MyURL" to ??
I have over 200 location.href URL not working with UIWebViewNavigationTypeLinkClicked :-S
Thanks to everyone can help me!
<script type="text/javascript">
document.getElementById("myAnchor").setAttribute("href", window.location.href);
var loc = document.getElementById("myAnchor").getAttribute("href");
var t = document.createTextNode(loc);
document.getElementById("myAnchor").appendChild(t);
</script>
Here is one way of doing it: document.getElementById() grabs a reference to the ID attribute of your anchor(s). The second argument of setAttribute(), "window.location.href" grabs a reference to the url in the current window and sets the href attibute in your anchor to this, however if you have a bunch of location.href()s declared in your code, then store these as a variable before the first line instead and then reference that variable at around the same line as where I have declared "loc". The variable "loc" declares a variable which stores a reference to the newly created href attribute you just declared in the previous line. Then I am declaring a variable "t" which creates a text node in the DOM, with the href from the previous line as the value this variable will hold. Lastly, I use document.getElementById to get "myAnchor" again and append the text node from the previous line to it. So now we can actually see the url in the link.
//Also, use a for loop to run this action 200 times and correct all of the hrefs on your page.
<script type="text/javascript">
for (var i=0;i<200;i++){
//run document.getElementById() and .setAttribute, .createTextNode, etc. here
}
</script>
Working fiddle: http://jsfiddle.net/1so33q4z/36/
I would not recommend using document.write(); as mentioned in the other person's post, as this causes the page to work in a way the DOM is not meant to (writes serialized text). Especially if you need to correct 200 of them. See this post Why is document.write considered a "bad practice"?

Categories

Resources