I have this
console.log(document.getElementsByClassName('value')[0].innerHTML);
Is there possibility to get this value from other page (without manually open this page)?
Can i get all value from page? Now when i use it i see only first value
Is there possibility to get this value from other page (without manually open this page)?
Without opening that page no, only from the current window (I assume this is what you mean when you're saying "page").
Can i get all value from page? Now when i use it i see only first value
Yes, document.getElementsByClassName('value') returns an array i.e exactly what you need. In your example you're just selecting the first element from the array, that's why you see only the first value.
Try this:
var all=document.getElementsByClassName('value');
for(var i=0;i<all.length;i++){
console.log(all[i].innerHTML);
}
....
Yes it's possible.
Create an AJAX request to get the website you need to extract values from. This StackOverflow answer provides dependency-free example code.
You can then parse the request using DOMParser, which is supported by all major browsers.
Set your value to local storage :
Set value to local storage localStorage.setItem('key', 'value');
Get value from another page localStorage.getItem('key');
Set your data
var data = document.getElementsByClassName('value')[0].innerHTML;
localStorage.setItem('value', data);
Get it from another page
localStorage.getItem('value');
Documentation : https://developer.mozilla.org/en/docs/Web/API/Window/localStorage
Otherwise you can use sessionStorage, Web SQL, IndexedDB & Cookies.
Related
So I have a JavaScript variable called addNumber which just adds a number by 1 to a div any time I click a button. But I'm using it on a website which has multiple pages, and every time I change pages, it resets the counter. I've used console.log() to check the variable multiple times, and it always resets back to zero any time I leave the page, even when I keep the tab open. This counter is kept at the top of the page for all to see, and I want it kept there in a navbar, kind of like the shopping cart on Amazon. Is there a way I can do something like that using only vanilla JavaScript?
Thank you.
You may find this link helpfull.
https://www.w3schools.com/jsref/prop_win_localstorage.asp
Quick answer you store key value pairs using a string tag to identify them:
localStorage.setItem("lastname", "Smith");
localStorage.getItem("lastname"); //this returns the string "Smith"
Edit: i do not recommend you doing this in a production enviroment. You should stick to the framework of the project. If the project has no framework or is just for school or learning purposes then i guess is a viable option.
You can store a variable in localStorage to access it somewhere else through
Try using:
function onClickevent(){
addNumber = addNumber +1
localStorage.setItem('counter', addNumber);
}
Then get it through
//Just assign it to your div
const getIt = localStorage.getItem('counter')
Here is some documentation on LocalStorage and how to use it :)
https://www.w3schools.com/jsref/met_storage_getitem.asp
https://blog.logrocket.com/localstorage-javascript-complete-guide/#:~:text=To%20get%20items%20from%20localStorage%2C%20use%20the%20getItem()%20method,in%20the%20browser's%20localStorage%20object.
The solution you can try is :
In the .js file at the end of all lines, type
window.localstorage.setItem("addNumber",addNumber);
The addNumber will be stored with an ID of addNumber.
To later retrieve, use :
window.localstorage.getItem("addNumber");
You may assign the above to a variable like
var number =....
Then console the number.
I hope this helps.
hello I have a small project I'm working on.
the project is calling an API with ajax and getting info about currencies, one of the things I'm stuck on is that I have to write them in cards that include a checkbox that has to stay activated after I refresh the page.
any suggestions?.. please I'm desperate
When you make your call on your API just set the checked value on the correct checkbox, please have in mind that setting checked=false will still give you a checked checkbox.
<input type="checkbox" checked>
One way to preserve information against a page refresh is to use localStorage.
LocalStorage allows you to store key:value variable pairs in the local browser. You can view the localStorage values for any given website in DevTools F12, on the Application tab. The variables are stored by website, and remain as they are until (a) they are deleted, or (b) browser cache is cleared. (For more info on when localStorage is cleared, see this answer).
LocalStorage is dead-simple to use:
let myPet = 'Cat';
localStorage.setItem('animal', myPet);
And to read it:
let myPet = localStorage.getItem('animal');
What you might want to do in your project, perhaps on a timer - or after the ajax call - is loop through your fields and create an object with all the fieldnames/values. Then use JSON.stringify to turn the object into text that you can store in a localStorage variable.
Note that you will need to write something that on page load ( $(document).ready() ) will see if the fields are empty and if there is a RECENT localStorage variable (so, you might want to create second localStorage variable (you can have MANY) that has the last-updated datetime) then you read the JSON string into a javascript object and populate your field values.
I would recommend using a dictionary, putting something unique like an ID of those currencies that are checked at that time.
If the new answer you get has the same currencies as before plus more, you can use that dictionary in memory to check those items again. If you don't get the previous response, you can just add those new items to avoid unchecking the checked currencies.
Exmaple:
var dictionary = {};
// here you should do a forEach in currently checked currencies
...
dictionary[id] = value; // (true, because it is the value of checked)
Hope it helps you.
This seems like a fairly simple question... I am trying to overwrite the data from cookie a with the data that is stored in cookie b but without changing either of the names of the cookies. Cookie b contains the particular user's defaults while cookie a stores the users current selections.
I have looked online and taken a few shots in the dark but, I have no leads! Everything that I've tried overwrites the entire cookie and I only want the data in cookie a to be changed, with no changes to the names of the cookies or to the data of any other cookies
Is this possible? If so how can I accomplish this task?
Thank you in advance!
Here's the code. It's commented enough to answer the question:
//first, get the "b" cookie's value
var cooks=document.cookie;
//just the "b" part of the cookie string
var bStartIndex=cooks.indexOf('b=')+2; //get the start of the b part of the string
var bEndIndex=cooks.indexOf(';',bStartIndex); //and the end of it
//and then extract the actual variable value from it
var b=cooks.slice(bStartIndex,bEndIndex!==-1?bEndIndex:null); //in case b was the last var, there would be no ; after it, so bEndIndex would be -1
//now, we set a to that
document.cookie='a='+b; //I don't THINK this will overwrite other cookies
I haven't tested it, but it SHOULD work. Tell me if it doesn't and I'll try to fix it
There are probably libraries out there that could make this a lot easier, if you're planning to use this in production
I will try to be as clear as possible.
Ok.I am making a simple tracker where it becomes very important for me to track user behaviour .I am using a javascript cookie for this purpose.
what I do :
After tracking the user,I get some data which I store in a javascript object literal.
var object = {
home-page :0-30,
brand-page:0-90,
mark-page :0-20,
home-page :0-10
}
I JSON.stringify the object to store the object value in a cookie.
MyQuestion :
Considering that there are two tabs opened and that I write some data in my cookie on second tab...would I get that latest data on window.focus of first tab if i read the same cookie?
Now when I come on the first tab,I want to update a property of my object(for example..home-page:0-30 is to be updated ),without altering
its order and updating the wrong property.
Can anybody guide me on this?
First you json is incorrect, it should contain only one unique id
var object = {'home-page' :'0-30', 'brand-page': '0-90', 'mark-page' : '0-20'}
Answer to you first question, yes you will get the updated data from second tab if both the tab have same domain.
Second Question: Yes you can update the same cookie and update the user info in same cookie.
You can check the steps at http://jsfiddle.net/raunakkathuria/fhe27/2/
I have a html page that sets a value onclick using a js function. I need to use this value in another html page. I am unable to do it. It seems to reset the value when I use the value from the second page. The .js file has been included in both the html pages. How do I retain the set value across multiple html pages?
Within JavaScript itself, you cannot keep track of variables across page loads. To pass the variable from one page to another, you will need to use a 'man in the middle' to help out. Either a cookie, or a query string.
A cookie would work great! I won't go into specifics of setting/getting cookies in JavaScript as there is excellent documentation here:
http://www.w3schools.com/JS/js_cookies.asp
Using those set and get methods (which of course you could customise to suit your needs):
First page:
var yourVariableToSave = 'I like cheese and crackers';
var numDays = 10; //How long the cookie should last.
setCookie('SomeCookieName', yourVariableToSave, numDays);
Second page:
var yourVariable = getCookie('SomeCookieName');
alert(yourVariable); //Displays 'I like cheese and crackers'
If you only want the cookie to last the duration of the current settings, you can modfy the setCookie function to not specify an expiry date.
If this is for a single request, a query string might be useful. To do this, you could append ?someQueryStringName=YourVariableValue to all links on the page, or inject the query string when the user is about to load another page. I won't go in depth with this option as I suspect a cookie may be a bit better.