Storings some fields in local storage - javascript

I want to store every created field in localStorage to get the ID's for later use.
This is a cordova app.
I'm creating field with javascript. An outside DIV, and input field and a button.
This input field and button has to be stored in localStorage for later use.
I have stored the div group ID, input Field ID and button ID in localStorage. I do not know if this is the best solution, but if not, then I would appreciate some pointers.
This is how I store it:
localStorage.setItem('inputGroup', 'input_area_group_' + id + '');
localStorage.setItem('inputField', 'input_field_' + id + '')
localStorage.setItem('delButton', 'delBtn_' + id + '');
Now.
This is the first time I'm acctualy using localStorage, so I do not have that big clue about it, but at least I'm trying.
When I store these 3 values into local storage and create another field with the excact same values. Will those then overwrite the other results or will there be an array with all the results in "inputGroup" f.eks? Like if I have 40 fields, I would like to have 40 values in "inputGroup" of localstorage.
This is because when I have created these fields, I would like to delete one of them if I want to. And then I tought that I could fetch the ID in localstorage that match the ID of the button that I pressed.
Is this a viable solution?
If not, then I'm happy with some pointers to what I could use that would make this much better.

LocalStorage is a dictionary, so the first part (the key) is unique. The second part, the value is tied to the key. Changing the value portion will replace, not add a new one. You could change the key value if you wanted instead.
Or you, can store the value as a delimited string, concatenating the new string each time. (However, concatenation is generally a slow operation). In this case, you could take the concatenated string and convert it to a JavaScript array.

Related

Trying to grab the 'save' from a dropdown option from a clone in Bootstrap and save the input to Local Storage

trying to save the input provided from the user in an input form that is cloned, so i want it to work for all the 'save' options, keep that text in local storage, and lastly to maintain that text in the input form even when the user refreshes the page, i've tried a bunch of different ways at my wits end, ha. here is fiddle: https://jsfiddle.net/dalejohn33/24u3vxmp/13/
$save.click((f) => {
var task = $("input:selected").val();
var getTask = JSON.parse(localStorage.getItem("input"));
var setTask = JSON.stringify(localStorage.setItem("input"));
console.log("text input has been saved");
}
thanks for any help!
There are some tasks here:
Get the right input's value
var task = $(f.target).closest('.dropdown-menu').next().val();
$(f.target).closest('.dropdown-menu') gets you to the dropdown and the input is next() to it.
localStorage.setItem accepts 2 arguments: (1) The key name (2) The data (You pass only the key).
In order to set the input's value to the value stored in localStorage, you need to store each input as a different key (not just input).
You need to iterate the inputs and set its value from localStorage.
Since the value you store is string, you don't need to stringify / parse.
Another point is the inconsistency name and id. The first element (the one you clone later) has none. Also the id and name are different values because you increase it between (length++)
https://jsfiddle.net/moshfeu/kw8jfg1m/32/

activating checkbox on load with javascript or jQuery

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.

JSON user search

I have the following gist with a JSON database and an XHR object.
The user parameter from getUsers(user) method is an input value.
I want select an user from the db via input search value. But i don't know how to set the http url or the searching algorithm.
I can select an user via: user.Name1 but how can i modify the entries after the dot .Name1 so it can be selected with the input value.
E.g: user. + "input value". I can't figured out.
I hope I inderstood you right, you want to access it via square brackets:
user[userValue] where userValue is your input variable
You can access on object like this user["Name1"] and as such can do this : user[input_value_variable]

Get object by HTML tag and remove from localstorage

this is my first question on stackoverflow.
and a little bit experience on code.
so I have a localstorage like this:
myDB: "[{"key:"123","label":"abc"}]
I have a div with "abc" as value:
<div id="name">abc</div>
And many id's div clone with different value
<div id="name">abc</div>
<div id="name">cde</div>
<div id="name">efg</div>
I want to read the value of the ID "name", make a if/else like looking "abc" are in the localstorage, if yes delete it with the key. else not delete.
I have thinking of using document.getElement to get value from ID and compare it to localstorage and using if else to do that thing. But there are many clone have that event to trigger the function to delete it. So the function don't know which ID's value to be compare and delete it.
I really awkward for this newbie question. But I have to ask, many thanks first :)
*New question:
I want to delete last element of the localstorage.
Can I convert localstorage to array then using array.pop(). Then convert the changed array again to the localstorage?
First, as was mentioned by others, id must be unique. You can use any other attribute instead, for example, class:
<div class="name">abc</div>
<div class="name">def</div>
<div class="name">ghi</div>
<div class="name">jkl</div>
<div class="other">mno</div>
Then, to query these elements, you could use document.getElementsByClassName("name") which will return you an array-like object. You can convert this object to an array of values using a combination of spread syntax and map method:
let values = [...document.getElementsByClassName("name")].map(e => e.innerHTML);
To work with the local storage you can use localStorage.setItem and localStorage.getItem. As you know, the local storage stores only strings, so JSON.parse and JSON.stringify methods will be helpful too.
Here is the example of code:
localStorage.setItem("myDB", '[{"key":"123","label":"abc"}, {"key":"456","label":"mno"}]');
console.log('Local storage before: ', localStorage.getItem("myDB"));
// extracting div values to an array
let values = [...document.getElementsByClassName("name")].map(e => e.innerHTML);
// creating a js object from myDB string
let db = JSON.parse(localStorage.getItem("myDB"));
// leaving only those elements, which labels are not in the values array
localStorage.setItem("myDB", JSON.stringify(db.filter(item => !values.includes(item.label))));
console.log('Local storage after: ', localStorage.getItem("myDB"));
JSFiddle link: https://jsfiddle.net/v03wpgq1/4/
id attributes should be unique on the page, otherwise only the last one on the page has the ability to be referenced easily (or at least, properly).
There should be a section that contains these which makes them easily queryable. Perhaps inside of an element with an id guaranteed to uniquely hold a set of name value pairs.
Using document.querySelectorAll is your best bet for finding these elements, and will be made easier by creating a structure that can be queried.
With a set of items to look for, it should be easy to iterate and test for values and keys inside of localStorage.

Qualtrics: Loop over embedded data fields?

I have a large set of embedded data fields that are called rnd1, rnd2, rnd3 etc. In a certain question block, I stored to each of these a certain value (each a different random number).
I also have a Loop and Merge question block, and in each round, I would like to access the stored data of a different field (i.e. in the 1st round I'd like to access whatever is in rnd1, in the 2nd round access rnd2 etc.) Can this be done in Qualtrics?
I tried something like:
Qualtrics.SurveyEngine.addOnload(function()
{
var trialNum = this.questionId.split('_')[0]; // getting the loop's current round number
var EDname = "rnd"+trialNum; // name of desired EF field
var rndNum = "${e://Field/" + EDname + "}"; // this is where I'd like stored the right ED value
// some more code that uses rndNum
});
but this does not work. It seems that while EDname gets the right string, I cannot access the value of that embedded field this way (though var rndNum = "${e://Field/rnd1} does work and returns the right value, so the problem seems to be in the looping strucutre).
If I cannot loop over the different fields in the JS code for some reason, is there another clever way to get that done in Qualtrics? For example, I thought it may be possible to use the different field names in the Loop and Merge section as "Field 2", but this seem to require me setting manually each and every ED field name.
Thanks.
Piped embedded data fields are resolved on the server before the page gets sent to your browser. So, it is impossible to dynamically create an embedded data field name and resolve it on the client side with JavaScript.
The way you are doing it with a loop & merge field is the best way.

Categories