activating checkbox on load with javascript or jQuery - javascript

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.

Related

How can I store a JavaScript variable in local storage?

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.

get Elements By Class Name from other page

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.

Working with cookies in javascript

For an assignment I had a few weeks ago we were asked to create two divs, one which collects and saves diary entries and one which displays the diary entries. We were asked to use the HTML form element and this should be proccessed using JS. Since it wasn't a server-side assignment were were asked to store the submitted diary entries using cookies I didn't get the assignment out and since the lecturer never posted the solution or went through a solution I was wondering if someone would be able to look at mine and show me how to do it. I was unsure how to actually set the cookie and return it. I'll also post a link to the js fiddle if that helps anyone.
So in short, I want to be able to save the values of the input box one the save entry button is clicked, and show this value once show diary is clicked
Thanks in advance
HTML
<form name ="name" onsubmit="return doSomething();">
Please Enter Your Diary Entry: <input type="text" name=“somename” id="frm_somename"/>
<input type="submit" name="Submit" value="Save Entry" />
</form>
<div id = "1">
<button id="button" onclick="y();">Show Diary</button>
</div>
JS
doSomething = function() {
// get the data from the form
var textValue = document.getElementById("frm_somename").value;
// the rest of the code goes here
// return false to stop form going somewhere - NB
return false;
}
Here's the link for the js fiddle also if that's any help https://jsfiddle.net/jon123/m957kc84/
You can do this pretty easily using just vanilla javascript... JavaScript can create, read, and delete cookies with the document.cookie property. This resource should answer all of your questions.
Also you are going to need to rewrite your JS... currently you dont have an appropriate click handler function created among some other issues.
You can achieve this in Javascript in two ways:-
Using Cookies
To simplify your work with cookies, you can use the js-cookie library. So, adding data to cookie can be easily achieved as follows:-
Cookies.set('diaryEntry1', 'This is a test diary entry.');
//In order to get the values stored in a cookie, you can do this-
Cookies.get('diaryEntry1');
When creating a cookie you can also pass an Array or Object Literal instead of a string in the value. If you do so, js-cookie will store the string representation of the object according to JSON.stringify:
Cookies.set('diaryEntries', { entry1: 'Diary entry 1', entry2: 'Diary entry 2' });
//When you will try to get this, it will return a string representation of the object.
Cookies.get('diaryEntries'); // => '{"entry1":"Diary entry 1", "entry2":"Diary entry 2"}'
Using localStorage
Local storage is a part of web storage, which itself is part of the HTML5 specification. In simple terms, all that localStorage does is store named key/value pairs locally and unlike cookies this data persists even if you close your browser or turn off your computer.
window.localStorage.setItem('diaryEntry1', 'This is a test diary entry.'');
window.localStorage.getItem('diaryEntry1');
The support for localStorage is pretty good for an HTML5 specification; it is supported by all the major browsers and even IE8, so the only thing you might need to be wary of is IE7 if you’re still supporting that.
In my opinion, you should go for localStorage since my guess would be that you would like to keep the data even after the user closes the browser. Hope this helps!

Manipulaitng javascript cookie on blur , focus ,onload and tabclose?

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/

How to save 4 drop down list selections to a cookie, and set drops if cookie present

So I am using jQuery and have setup the jquery cookie plugin.
I have 4 drop down lists on my page, and I want to save the user's selections in a cookie, so when they come back to the page I automatically pre-select their previous selections.
I added a class to all my drop downs "ddl-cookie", and I was just thinking if I could somehow loop through all the drop down lists using the class, and save the selection and also loop to set the selections when the user returns to the page.
$(".ddl-cookie").each(function() {
});
It seems that given a cookie name, I can save a single key/value in the cookie.
So I'm guessing the only way for me to do this would be to have a comma separated list of drop down list names and values (selection value)?
You are correct. Cookies are intended to store a single piece of data, so the most common way to handle this is to serialize your data into an easy to retrieve format. That format is up to you, but you might use something like:
field_1=value1&field_2=value&...
You might want to also encode this data--remember that cookies are transferred as part of the request header. The pseudo code would go something like this:
// Store the data, using your own defined methods
data = serialize_data(data);
data = encode_data(data);
cookie = data;
// Retrieve the data using your own defined methods
data = cookie;
data = unencode_data(data)
data = deserialize_data(data)

Categories