How to add multiple text to local Storage HTML5 - javascript

I created a few functions and some input boxes with a table to show the data when page is reloaded. The issue I am having is how do I get multiple inserts to local storage and be able to show all the data on the table with a loop statement. Also is there way to show the data right away instead of reload. I guess I am just confused with local Storage and I was trying to see how it works.
https://jsfiddle.net/zzLumrsd/
<!DOCTYPE>
<html>
<head>
<title> Local storage</title>
<style type="text/css">
table#table1{
width: 10%;
background-color: #gray;
}
</style>
<script>
function saveMy(){
var fieldValue = document.getElementById('textfield').value;
localStorage.setItem('text', fieldValue);
}
function load(){
var storedValue = localStorage.getItem('text');
if(storedValue){
document.getElementById('textfield2').value = storedValue;
}
}
function removeMy() {
document.getElementById('textfield').value = '';
localStorage.removeItem('text');
}
</script>
</head>
<body onload="load()">
<input type="text" id="textfield" />
<input type="button" value="save" onclick="saveMy()"/>
<input type="button" value="remove" onclick="removeMy()"/>
<hr/>
<table id="table1" border="1">
<tr>
<th>text</th>
</tr>
<tr>
<td>
<input type="text" id="textfield2" />
</td>
</tr>
</table>
</body>
</html>

As far as I understand, you want to store multiple strings into localStorage. You could achieve that using the following:
How
To achieve this, you would store all the Strings in an array. We can then put this into localStorage. In the examples, I will be using 'names' as the localStorage item name. An array can't be put into localStorage so we have to make it a String using JSON.stringify to do that.
Examples
Setting the Item
var vals = [];
vals.push('Bob');//Add the text 'item1' to vals
localStorage.setItem('names', JSON.stringify(vals));
Getting the Item
vals = JSON.parse(localStorage.getItem('name'));
In this, we will get the item from localStorage, and make the string into an array again using JSON.parse
Further Explanation
localStorage is an browser API that allows us to store data on a users computer. localStorage is somewhat like cookies but are less limited and don't expire.
We want to store in this case, names, in localStorage. You can store anything JavaScript in localStorage. Stack Overflow stores timestamps and a few other things in your localStorage.
Each item, or 'thing' in localStorage, has a name, and a value.
When using localStorage.setItem('name', 'Bob'), you create an item called name and it's value is Bob
This is all well and good until you want to add a second name. JavaScript has arrays which can store multiple values in one 'variable'. This means you can store multiple names, in one variable/item. The following is an example of an array
var myArray = ['Bob', 'Joe', 'Phil'];
That array has three values: Bob, Joe, and Phil. You can add an item into an array using Array.push(). I'm going to link an article on arrays here
Okay, so now you have your three values in an array and you want to store it. localStorage values can only be strings! JSON is is a special type of 'variable' similar to a JavaScript object, you can learn about it here. In simple terms, an array is 'JSON'.
Because localStorage only takes strings, we must turn our array (JSON) into a string which we can store. The way this is done is JSON.stringify(ARRAY_HERE). This will return a string like:
"["Bob","Joe","Phil"]"
Now that our array is a string, we can put it into localStorage using localStorage.setItem().
What do we do when we want to retrieve this?
To retrieve the array, we will use localStorage.getItem(). In localStorage.getItem() you put the name of the item you wish to access and it will return it. But the problem is it is still a string. That's where JSON.parse() comes in. This will convert our 'stringified' array into an actual array.
What does this all have to do
I want to store three names in localStorage
How would you do that? It's simple, what you add the names to the array using .push(), then you store it. When you want to display it, use the localStorage.getItem() I described before.
Further Reading
I wrote a lot but that might not be enough, check out the following:
MDN Arrays
localStorage Article
w3schools JSON

Related

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.

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.

Copying a ColdFusion cfparam array into a JavaScript array

I've have a CF page who's inventory search form, frm_inv post's back to itself. frm_inv's main table of records, tbl_inv, uses a tablesorter. A hidden input (sort_list) is used in conjunction with a cfparam to keep track of tbl_inv's sortList:
main.cfm
<cfparam name="form.sort_list" type="string" default="1,0">
<form id="frm_inv" action="main.cfm" method="post">
<input name="sort_list" type="hidden" value="#form.sort_list#"/>
<table id="tbl_inv" class="tablesorter">
...
</table>
</form>
When frm_inv is submitted, CF uses sort_list in $(document).ready() to restore tbl_inv's sort order:
$(document).ready(function(){
var sort_list_str = <cfoutput>"#form.sort_list#"</cfoutput>;
var sort_list = sort_list_str.split(",");
$("#tbl_inv").tablesorter({
textExtraction: ['complex'],
sortList:[[sort_list[0],sort_list[1]]]
}).bind("sortEnd", function(sorter) {
var sl = sorter.target.config.sortList;
$("input[name='sort_list']").val(sl.toString());
});
});
I would rather use arrays than convert a comma separated string into an array like I'm currently doing
<cfparam name="form.sort_list" type="string" default="1,0">
to
<cfparam name="form.sort_list" type="array" default="ArrayNew(2)">
however I need to know the proper javascript and coldfusion syntax in order pose everything that's relevant in arrays exclusively.
Copying a ColdFusion ... array into a JavaScript array
Why? For the most part, HTTP only transmits strings, so there is no translation between client and server complex types. Unless you are doing something more than just passing the sort value back and forth, converting between client and server side arrays is just an unnecessary complication. It is simpler to leave the value as a string and do any splitting or parsing on the client side.
You did not really explain what problem you are trying to solve, but .. there is nothing inherently wrong with the current approach. However, it could be simplified a bit. There is no need to cfoutput the variable again here:
(A) var sort_list_str = <cfoutput>"#form.sort_list#"</cfoutput>;
Since you already stored the current form.sort_list value in a hidden form field, the above is redundant. Instead, just read the field's value with javascript ie
(B) var sort_list_str = $("input[name='sort_list']").val();
Having said that, if you really prefer to work with arrays, you could store a JSON string representation of the arrays instead. Then use parse() and stringify() to convert the arrays back and forth. Same net effect as your current method, but a bit simpler in terms of code.
Form:
<cfparam name="form.sort_list" default="[[1,0]]">
...
<input id="sort_list" name="sort_list"
type="hidden" value="#encodeForHTML(form.sort_list)#" />
...
JQuery:
$(document).ready(function(){
$("#tbl_inv").tablesorter({
textExtraction: ['complex'],
sortList: JSON.parse($("#sort_list").val())
}).bind("sortEnd", function(sorter) {
var sort_arr = sorter.target.config.sortList;
$("#sort_list").val(JSON.stringify(sort_arr));
});
});
For creating a JavaScript variable from a ColdFusion variable, you can use toScript() function.
var #toScript(ListToArray(form.sort_list), "sort_list")#;
This can be used for wide range of variable types such as strings, arrays, structures etc.
Needs specific syntax to use an array in cfparam: ColdFusion CFParam Can Use Struct And Array Notation
<cfparam name="form.sort_list" type="array" default="#ArrayNew( 2 )#">

javascript add array item to form value

I have a form with a hidden field:
<input type="hidden" name="newdesc[]" id="newdesc" />
I have an autolookup and a plus button so the plus button adds the field value of the autolookup to an array:
newdesc_a.push(document.getElementById('autocomplete1').value);
var x=document.getElementById("businesslist");
x.innerHTML=newdesc_a;
document.getElementById('newdesc').value = newdesc_a;
(newdesc_a is previously declared as an array)
It updates the div OK (businesslist) but does not assign the value to the newdesc.
I am sure it is simple but it is driving me mad!
Given the name="newdesc[]" attribute, I assume PHP on the server side. When you submit a key two or more times, only the last value is available in the script via $_REQUEST. In the case of a key ending with [] , instead, PHP builds an array and make it available to your script via $_REQUEST['key']. Note that this behavior is application-specific, there's nothing like an array at the HTTP level.
Now, you want to pass an array from the client side (Javascript) to the backend (PHP). You have two options:
Use a proprietary format, eg separate values by commas or colons, and split the string on the server side (or you can use an existing format like JSON, XML, ...)
Take advantage of the PHP syntax for passing arrays
It seems you want to adopt the 2nd way, so you will want to submit a form like the following
<input name="email[]" value="joel#example.com" />
<input name="email[]" value="mark#people.com" />
<input name="email[]" value="bill#hello.com" />
PHP will be able to access a plain array in $_REQUEST if you build your form like this. Now, you have the problem of building the form programmatically on demand. This is the best I can think of (jQuery):
var email = $("#autocomplete").value;
// if you really need to keep emails in an array, just
// emails.push(email);
$('<input type="hidden">').attr({
name: 'email[]',
value: email
}).appendTo('#myForm');
You want to assign a particular value of array to that element?
You can use like this.
document.getElementById('newdesc').value = newdesc_a.index;
where 'index' is the index of array. replace it.

storing and retrieving 100-element array

I am using Greasemonkey/Tampermonkey to visit pages and make a change to a 100-element table based on what's on the current page.
Short term storage and array manipulation works fine, but I want to store the data permanently. I have tried GM_getValue/GM_setValue, GM_SuperValue, localStorage, and indexedDB, but I am clearly missing something fundamental.
Nothing seems to allow me to write the array into the permanent storage and then read it back into a variable where I can access each element, such that variablename[32] is actually the 32nd element in the table (Well, 33rd if you start counting at zero, which I do).
I need access to the entire 100-element table while the script is running, because I need to output some or all of it on the page itself. In the most basic case, I have a for loop which goes from 0 to 99, printing out the value of variablename[i] each time.
I have no predisposition to any method, I just want the frickin' thing to work in a Greasemonkey/Tampermonkey script.
Towards the top of the script I have this:
for (var i = 0; i <= 99; i++) {
currentData[i] = localStorage.getItem(currentData[i]);
}
The purpose of the above section is to read the 100 entries into the currentData array. That doesn't actually work for me now, probably because I'm not storing things properly in the first place.
In the middle, after modifying one of the elements, I want to replace it by doing this:
localStorage.setItem(
currentData[specificElementToChange], differentStuff);
The purpose of the above is to alter one of the 100 lines of data and store it permanently, so the next time the code at the top is read, it will pull out all 100 entries, with a single element changed by the above line.
That's the general principle.
I can't tell if what I'm doing isn't working because of some security issue with Firefox/Chrome or if what I want to do (permanently storing an array where each time I access a given page, one element changes) is impossible.
It's important that I access the array using the variable[element] format, but beyond that, any way I can store this data and retrieve it simply is fine with me.
I think you're going about this wrong. LocalStorage stores strings so the simplest way to store an array in LocalStorage is to stringify it into JSON and store the JSON. Then, when reading it back, you parse the JSON back into an array.
So, to read it in, you do this:
var currentData = JSON.parse(localStorage.getItem("currentData") || "[]");
To save your data, you do this:
localStorage.setItem("currentData", JSON.stringify(currentData));
Working demo: http://jsfiddle.net/jfriend00/6g5s6k1L/
When doing it this way, currentData is a variable that contains a normal array (after you've read in the data from LocalStorage). You can add items to it with .push(), read items with a numeric index such as:
var lastItem = currentData[currentData.length - 1];
Or, change an item in the array with:
currentData[0] = "newValue";
Of course, it's just a normal array, so you can use any array methods on it.

Categories