Access variables from another JavaScript file - javascript

I need to get a variable currentID from renderermain.js and use it in renderermem.js.
However, I need to do this without having to add this to mem.html:
<script src="renderermain.js"></script>
<script src="renderermem.js"></script>
Because I cannot mix these two.
I have tried:
renderermain.js
globalVariable={currentID:activeID};
renderermem.js
var currentID = globalVariable.currentID;
But this doesn't work.
Note: I am switching html files at this point from main.html (using renderermain.js) to mem.html (using renderermem.js).
Does anyone have any ideas?
Thanks.

Basically there are two ways to pass variables between web pages. The first method is to use sessionStorage, or localStorage. The second method is to use a query string with the URL.
To use sessionStorage or localStorage:
This goes in the first web page:
// "myVariable" is the sessionStorage variable name
// "variable_one" is the variable string value
sessionStorage.setItem("myVariable", "variable_one);
// This goes in the second web page:
// Retrieve the sessionStorage variable
var myVariable = sessionStorage.getItem('myVariable');
Query String with URL:
Pass a string as a parameter.
Example:
Go to filename
When Go to filename is clicked, filename.html is loaded with the query string
"?data1|data2|data3"
appended to the filename in the address bar. To get the query string into variables,
use:
var queryString = location.search.substring(1);
The variable queryString now has the value
"data1|data2|data3"
To break these out into individual variables use split:
var a = queryString.split("|");
// which creates an array
Then get the values out of the array and put them into variables:
var value1 = a[0];
var value2 = a[1];
var value3 = a[2];
Now:
value1 == "data1", value2 == "data2", value3 == "data3"

Related

Click a button or a link to set as a default option using <select> another page? [duplicate]

I have a page1.html which contains set of data
{'key1':'value1','key2':'value2','key3':'value3'}
and a link
<a target='_blank' href='page2.html'>Click To Navigate</a>
which will navigate to page2.html.
I would like to ask how can I pass all the data above in page1.html to page2.html so that I can use them in page2.html.
What I tried to use is localStorage, but I can store only 1 set of data at a time, so if in my page1.html have many set of data, same key but different value they will be overlapped when I store them in localStorage, then I can not pass all these set of data to the page2.html.
Anyone got an idea?
Thank you so much
You can do it using Javascript, there's no restriction of which kind of object you can pass.
For instance, if you have several key-value objects:
var firstData = {
'key1' : 'value1',
'key2' : 'value2'
};
and
var secondData = {
'key1' : 'value3',
'key2' : 'value4'
};
you could enclose them using a Javascript array:
// This is on page1.html
var myData = [ firstData, secondData ];
and pass that array using localStorage.
Javascript on page1.html
// Set the variable
localStorage.setItem( 'objectToPass', myData );
Javascript on page2.html
// Get the variable
var myData = localStorage['objectToPass'];
localStorage.removeItem( 'objectToPass' ); // Clear the localStorage
var firstData = myData[0];
var secondData = myData[1];
alert('firstData: ' + firstData + '\nsecondData: ' + secondData);
If you want to use javascript to do this, you can do the following (explains it really well)
- https://www.boutell.com/newfaq/creating/scriptpass.html
Also, you can use HTML5 to pass objects from a page to another page of your choise. In order to do this, you would create a session like this:
sessionStorage.setItem('key', 'value');
And then to read the session you would do this:
sessionStorage.getItem('key');
This is a really good example on a webpage on how this can be achieved:http://demos.w3avenue.com/html5-unleashed-tips-tricks-and-techniques/sample-09-sessionstorage-demo.html
You can use the localstorage with JSON method (JSON.parse) to parse a JSON string and construct the JavaScript value or object described by the string. The reverse operation is accomplished by the other method (JSON.stringify) to convert a JavaScript object or value to a JSON string.
javascript on the first page:
var data = {'key1':'value1','key2':'value2','key3':'value3'};
localStorage.setItem("object_name",JSON.stringify(data));
javascript on the second page.
var data = localStorage.getItem("object_name");
localStorage.clear(); //clean the localstorage
var value1 = JSON.parse(data).key1;
var value2 = JSON.parse(data).key2;
So now value1 and value2 in the second page contain the value of value1 and value2 of the first page.

remember all values in an array using cookies - javascript

i want to be able to remember all values in an array using cookies, but do not know how. I am also using js-cookies.
Here is my code:
var usernames = new Array();
var input = $('#input').val();
usernames.push(input);
// each time something is inputted, it'll be saved to the
// array usernames. I want it so that when refreshed, all
// of the inputs remain in 'usernames'
alert(usernames);
As mentioned, localStorage is a better place to store this data, but using cookies follows the same steps, just need to get a set/get method for Cookies. First you need to see if there is a value. If there is you need to parse it. After you update the array, you need to convert the value to a string and store it.
//Read local storage to see if we have anything saved
var lsUserNames = localStorage.getItem("usernames");
//Get the usernames array
var usernames = lsUserNames ? JSON.parse(lsUserNames) : [];
//Just using prompt to get the username instead of making form
var uname = window.prompt("Enter Name");
if(uname) usernames.push(uname);
//set the updated array to local storage
localStorage.setItem("usernames", JSON.stringify(usernames));
console.log(usernames.join());

How to point to an JS Array by Name in the Form of String?

I have a JS array.
//This is Dynamic, I maynot know the name in the beginning
var myArray = ["apple","ball","cat"];
var NameOfArray = "myArray";
How can I access myArray if I know only it's name in the form on String?
In PHP, I would use $$. How Do I do that in JS?
Depending on where the array is defined, you can access it directly i.e. if it is defined globally as in your example:
console.log(window[NameOfArray][1]); // Outputs "ball"
Use:
eval("myArray")
It is an array which has the contents of myArray.
If you're able to control the name of the variable NameOfArray, i.e. control the code, you could just set it as a variable on the window in that line using eval
var myArray = [1,2,3];
window.theArrayIWant = eval('myArray');
then using theArrayIWant moving forward

Not able to retrieve key value

I have data in format
var data = "{key1=value1,key2=value2}"
I want to perform something like when I have key1 i should get value1 in return.
For example:
var val = data[key1];
//val value should be value1
There are a few issues here. The first is that your 'data' variable in its current form is just a string. You would need to remove the enclosing quotes, and replace your ' = ' with ' : ' which will make it a JavaScript object so you can index into it.
The second issue is that 'value1' in your object is not defined. You would either need to create another variable called 'value1' and initialize it, then stick it into your data object, but their are better ways to go about it if this is what you are trying to accomplish.
If you are just creating key/value pairs, then you could do something like:
var data = {key1:'value1',key2:'value2'};
You could then access the 'key1' value by doing the following:
var val = data['key1'];
or
var val = data.key1;
Here is a fiddle to illustrate how it works: http://jsfiddle.net/LxjN4/

Store object from local storage into variable

I am trying to retrieve a object from localstorage and trying to load it into a variable . How can i do this ? This is where i m stuck
var messageStorage={};
messageStorage.retrieve = function () {
var storageString = localStorage.getItem(credentials.mobileNumber);
var storageObj = JSON.parse(storageString);
// whats should go here for messageStorage to be equal to storageObj
};
On messageStorage.retrieve(); the variable messageStorage must contain the value from localstorage.
with localStorage the data is actually stored as a string.
And you use JSON.parse to return the value
JSON.parse() Returns the Object corresponding to the given JSON text.
Example :
JSON.parse('{}'); // {}
JSON.parse('true'); // true
JSON.parse('"foo"'); // "foo"
JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
JSON.parse('null'); // null
But i saw that you want to return the variable. So what's the type of this variable ? Number, String, Boolean ? You can convert from String to what you need
localStorage allows you to save only strings, so if you have to save an object you should save it as a JSON string or you can use this library to solve your issue
first of all we can't store objects to localstorage, only strings are allowed:
localStorage.setItem("test", JSON.stringify(jsondata));
var item = JSON.parse(localStorage.getItem("test"));
now you have json data to parse it and get the value.

Categories

Resources