LocalStorage storing multiple div hides - javascript

I am using a simple code to hide multiple divs if the link to hide them is clicked.
On one of them I have local storage set-up to remember of the div is hidden or not.
The thing is this. How can I write a code to make local storage remember the hidden state of multiple divs WITHOUT having to put localstorage.setItem for each individual div. Is it possible to store an array with the div ids and their display set to true or false to decide if the page should show them or not?
**********EDITED************
function ShowHide(id) {
if(document.getElementById(id).style.display = '') {
document.getElementById(id).style.display = 'none';
}
else if (document.getElementById(id).style.display = 'none') {
document.getElementById(id).style.display = '';
}

Like you said, you already have an array storing all your state. You can serialize this using JSON.stringify() and put the result into localStorage.
// your array
var divstate = [ ... ];
// store it
localStorage.setItem( 'divstate', JSON.stringify( divstate ) );
If you want to retrieve the array again, use JSON.parse():
// restore
var divstate = JSON.parse( localStorage.getItem( 'divstate' );
EDIT
To store the actual ids of all divs, you probably will use something like this
var divstate = {
'divid1': true,
'divid2': false,
...
};
This can easily be used with the above pattern.
2nd EDIT
For the above code I would suggest loading the state variable once at page load using the above statement.
Then transform the function like this:
function ShowHide(id) {
var el = document.getElementById(id);
if ( divstate[id] === true ) {
divstate[id] = false;
el.style.display = 'none';
} else {
divstate[id] = true;
el.style.display = '';
}
localStorage.setItem( 'divstate', JSON.stringify( divstate ) );
}
That way the divstate is updated and stored with each function call.
Note, that I would not recommend this, if the number of divs is too high, but for smaller amounts this should be sufficient.

Related

How to retrieve multiple select values from sessionStorage and put them into the original form field

I want to store values from a form input field that has a tags input functionality using select multiple and automatically retrieve them back after the form was sent. Basically, what I am trying to achieve is to just keep them in the input field after form submission. With them being tags, this adds convenience to the user since you can just add/delete some of the inputs and reload the page.
I have successfully written a piece of code that stores the array in sessionStorage after clicking the submit button, where pmids[]is the id of the select element:
function store() {
var select = document.getElementById('pmids[]');
var pmids = [...select.options]
.filter(option => option.selected)
.map(option => option.value);
sessionStorage.setItem("pmids", JSON.stringify(pmids));
}
I am struggling with getting the values back into the form field though, this attempt does not seem to work:
var storedPmids = JSON.parse(sessionStorage.getItem("pmids"));
if (storedPmids !== null) {
document.getElementById("pmids[]" options).each(function() {
for (var i = 0; i < storedPmids.length; i++) {
if (this.value == storedPmids[i]) {
this.selected = true;
}
}
});
}
Speaking of this line:
document.getElementById("pmids[]" options)
This is not how you access the options of a <select> element. Instead you should call:
document.getElementById("pmids[]").options
Furthermore, each is a jQuery method. The vanilla JS equivalent of each is forEach, which, in fact, only works with arrays and nodelists. Hence you need to convert your options collection into an array first:
var options = Array.from(document.getElementById("pmids[]").options);
Finally, this inside forEach refers to the window object, so you need to use a callback function with a parameter. Full code:
var storedPmids = JSON.parse(sessionStorage.getItem("pmids"));
if (storedPmids !== null) {
var options = Array.from(document.getElementById("pmids[]").options);
options.forEach(function(option) {
for (var i = 0; i < storedPmids.length; i++) {
if (option.value == storedPmids[i]) {
option.selected = true;
}
}
});
}

Problems with setting a data attribute using vanilla javascript

I've been working with a set of data that is returned from a fetch call to a Lucee coldfusion server. The data returned is a structure that looks like this:
{success: true, new_case_number: caseno}
This is how everything starts on the Javascript side. I've setup a submit event handler for the form element using form.addeventlistener('submit', inquirySubmit). This is what that looks like:
function inquirySubmit(){
event.preventDefault();
var data = [this.lastname.value, this.caseno.value, this.id.value];
fetch(`../CFC/flowstatus.cfc?method=setDebtorInfo&action=inquiry&trusteeID=${slush}&values=${data}`, {
method: 'post'
})
.then( res => res.json())
.then( (data)=>{
if( data.SUCCESS == true ){
setNewValues(this.lastname.value, data.NEW_CASE_NUMBER)
background.style.transform = 'scaleY(0)';
setTimeout( ()=>{
inquiryEditForm.reset();
inquiryEditForm.display = 'none';
}, 1000 )
}
if( data.SUCCESS == false) alert('Argh!')
})
} // END FUNCTION
if the data.SUCCESS variable is set to true I use the setNewValues function:
function setNewValues(lastname, caseno){
console.log(`Lastname: ${lastname}\n Caseno: ${caseno}.`)
var dm = document.querySelector('.debtor-main');
var cn = dm.querySelectorAll('div');
cn.forEach( (div)=>{
if( div.dataset.caseNo == caseno){
div.setAttribute('data-case-no', caseno )
var span_lastname = div.querySelector('#lastname');
var span_caseno = div.querySelector('span[id=caseno]');
span_lastname.innerHTML = lastname;
span_lastname.setAttribute('data-case-no', caseno );
span_caseno.innerHTML = caseno;
span_caseno.setAttribute('data-case-no', caseno );
}
})
} // END FUNCTION
I've added some console.log bits in there to make sure I was getting the right values and they are good. As you can see I'm changing the innerHTML values of some span elements to reflect the changes that the user has typed in. The variable span_lastname gets reset no problem. But neither the data-case-no attributes nor the span_caseno.innerHTML respond to the setAttribute('data-case-no', caseno) call. The thing that's really irritating is that I know I'm accessing the right element with the span_caseno variable because I can effect the style attribute like so:
span_caseno.style.opacity = 0;
And it works.
If anyone has some suggestions it would be very helpful. I'd be happy to change the code up completely, so fire away.
Try using:
span_lastname.dataset.caseNo = caseno;
span_caseno.dataset.caseNo = caseno;
Instead of using setAttribute.
function setNewValues(lastname, caseno){
console.log(`Lastname: ${lastname}\n Caseno: ${caseno}.`)
var dm = document.querySelector('.debtor-main');
var cn = dm.querySelectorAll('div');
Array.from(cn).map( (div)=>{
if( div.dataset.caseNo == caseno){
div.setAttribute('data-case-no', caseno )
var span_lastname = div.querySelector('#lastname');
var span_caseno = div.querySelector('span[id=caseno]');
span_lastname.innerHTML = lastname;
span_lastname.setAttribute('data-case-no', caseno );
span_caseno.innerHTML = caseno;
span_caseno.setAttribute('data-case-no', caseno );
}
})
} // END FUNCTION

How would I use local storage for a to do list?

I am being asked to have a to do list and save each task (that the user supplies as well as original) through local storage. My teacher did a very simple demo on something completely different and I spent a few hours trying to figure it out. When I looked at the solution, I honestly cannot figure it out. It looks really complicated, and I don't even know where to start. If anyone can give me any hints, that would be awesome!
My code:
let ul = document.querySelector('ul');
let newItem = document.querySelector('input[type=text]');
let checkbox = document.createElement('input');
checkbox.setAttribute('type', 'checkbox');
function output() {
let newTodo = document.createElement('li');
newTodo.innerText = newItem.value;
newTodo.classList.add('todo');
let ulAppend = ul.append(newTodo);
ul.append(newTodo);
let checkboxAppend = newTodo.append(checkbox);
newTodo.append(checkbox);
newItem.value = '';
}
let button = document.querySelector('.btn');
button.addEventListener('click', output);
ul.addEventListener('click', function(e) {
if (e.target.tagName === 'LI') {
e.target.remove();
} else if (e.target.tagName === 'INPUT') {
e.target.parentElement.classList.toggle('finished');
}
});
My teacher's code/local storage solution:
const todoForm = document.getElementById("newTodoForm");
const todoList = document.getElementById("todoList");
// retrieve from localStorage
const savedTodos = JSON.parse(localStorage.getItem("todos")) || [];
for (let i = 0; i < savedTodos.length; i++) {
let newTodo = document.createElement("li");
newTodo.innerText = savedTodos[i].task;
newTodo.isCompleted = savedTodos[i].isCompleted ? true : false;
if (newTodo.isCompleted) {
newTodo.style.textDecoration = "line-through";
}
todoList.appendChild(newTodo);
}
todoForm.addEventListener("submit", function(event) {
event.preventDefault();
let newTodo = document.createElement("li");
let taskValue = document.getElementById("task").value;
newTodo.innerText = taskValue;
newTodo.isCompleted = false;
todoForm.reset();
todoList.appendChild(newTodo);
// save to localStorage
savedTodos.push({ task: newTodo.innerText, isCompleted: false });
localStorage.setItem("todos", JSON.stringify(savedTodos));
});
todoList.addEventListener("click", function(event) {
let clickedListItem = event.target;
if (!clickedListItem.isCompleted) {
clickedListItem.style.textDecoration = "line-through";
clickedListItem.isCompleted = true;
} else {
clickedListItem.style.textDecoration = "none";
clickedListItem.isCompleted = false;
}
// breaks for duplicates - another option is to have dynamic IDs
for (let i = 0; i < savedTodos.length; i++) {
if (savedTodos[i].task === clickedListItem.innerText) {
savedTodos[i].isCompleted = clickedListItem.isCompleted;
localStorage.setItem("todos", JSON.stringify(savedTodos));
}
}
});
Even though my code is more simpler (at least from what I can tell), it works exactly as his code does.
Local storage saves a JSON object to the user's computer. You should create an array of todos, append that array with every new todo, then set that item to local storage.
let ul = document.querySelector('ul');
const savedTodos = JSON.parse(localStorage.getItem("todos")) || []; // Retrieves local storage todo OR creates empty array if none exist
let newItem = document.querySelector('input[type=text]');
let checkbox = document.createElement('input');
checkbox.setAttribute('type', 'checkbox');
function output() {
let newTodo = document.createElement('li');
newTodo.innerText = newItem.value;
newTodo.classList.add('todo');
ul.append(newTodo);
newTodo.append(checkbox);
savedTodos.push({task: newItem.value, isCompleted: false}); // Appends the new todo to array
localStorage.setItem("todos", JSON.stringify(savedTodos)); //Converts object to string and stores in local storage
newItem.value = '';
}
I've annotated the solution you posted with some comments to help you step through it.
// Retrieve elements and store them in variables
const todoForm = document.getElementById("newTodoForm");
const todoList = document.getElementById("todoList");
// Get data stored in localStorage under the key "todos".
// The data type will be a string (local storage can only store strings).
// JSON is a global object that contains methods for working with data represented as strings.
// The `||` syntax is an OR operator and is used here to set an empty array as a fallback in case `localStorage` is empty
const savedTodos = JSON.parse(localStorage.getItem("todos")) || [];
// Create a loop the same length as the list of todos
for (let i = 0; i < savedTodos.length; i++) {
// Create an <li> element in memory (does not appear in the document yet)
let newTodo = document.createElement("li");
// Set the inner text of that new li with the contents from local storage.
// The savedTodos[i] is accessing data in the localStorage array.
// The [i] is a different number each loop.
// The `.task` is accessing 'task' property on the object in the array.
newTodo.innerText = savedTodos[i].task;
// Create a new property on the element called `isCompleted` and assign a boolean value.
// This is only accessible in code and will not show up when appending to the DOM.
newTodo.isCompleted = savedTodos[i].isCompleted ? true : false;
// Check the value we just set.
if (newTodo.isCompleted) {
// Create a style for the element if it is done (strike it out)
newTodo.style.textDecoration = "line-through";
}
// Actually append the new element to the document (this will make it visible)
todoList.appendChild(newTodo);
}
// `addEventListener` is a function that registers some actions to take when an event occurs.
// The following tells the browser - whenever a form is submitted, run this function.
todoForm.addEventListener("submit", function(event) {
// Don't try to send the form data to a server. Stops page reloading.
event.preventDefault();
// Create a <li> element in memory (not yet visible in the document)
let newTodo = document.createElement("li");
// Find element in the document (probably a input element?) and access the text value.
let taskValue = document.getElementById("task").value;
// Set the text of the <li>
newTodo.innerText = taskValue;
// Set a property on the <li> call `isCompleted`
newTodo.isCompleted = false;
// Empty out all the input fields in the form
todoForm.reset();
// Make the new <li> visible in the document by attaching it to the list
todoList.appendChild(newTodo);
// `push` adds a new element to the `savedTodos` array. In this case, an object with 2 properties.
savedTodos.push({ task: newTodo.innerText, isCompleted: false });
// Overwrite the `todos` key in local storage with the updated array.
// Use the JSON global object to turn an array into a string version of the data
// eg [1,2,3] becomes "[1,2,3]"
localStorage.setItem("todos", JSON.stringify(savedTodos));
});
// This tells the browser - whenever the todoList is clicked, run this function.
// The browser will call the your function with an object that has data about the event.
todoList.addEventListener("click", function(event) {
// the `target` of the event is the element that was clicked.
let clickedListItem = event.target;
// If that element has a property called `isCompleted` set to true
if (!clickedListItem.isCompleted) {
// update the styles and toggle the `isCompleted` property.
clickedListItem.style.textDecoration = "line-through";
clickedListItem.isCompleted = true;
} else {
clickedListItem.style.textDecoration = "none";
clickedListItem.isCompleted = false;
}
// The code above changes the documents version of the data (the elements themselves)
// This loop ensures that the array of todos data is kept in sync with the document
// Loop over the array
for (let i = 0; i < savedTodos.length; i++) {
// if the item in the array has the same text as the item just clicked...
if (savedTodos[i].task === clickedListItem.innerText) {
// toggle the completed state
savedTodos[i].isCompleted = clickedListItem.isCompleted;
// Update the localStorage with the new todos array.
localStorage.setItem("todos", JSON.stringify(savedTodos));
}
}
});
Keep in mind, there are 2 sources of state in your todo list. One is how the document looks, and the other is the array of todos data. Lots of challenges come from making sure these 2 stay in sync.
If somehow the document showed one of the list items as crossed out, but your array of data shows that all the todos are not completed, which version is correct? There is no right answer here, but state management will be something you might consider when designing apps in the future. Redux is a good js library with a well understood pattern that helps solve this problem. Hope this last comment doesn't confuse too much. Best of luck!
The important part is in (de)serializing the data. That means:
reading from localStorage (JSON.parse(localStorage.getItem("todos")) || [])
We add the default [] because if the todos key does not exist, we will get null and we expect a list
saving to localStorage (localStorage.setItem("todos", JSON.stringify(savedTodos)))
We need JSON.parse and its complementary operation JSON.stringify to parse and save strings because localStorage can store only strings.
In your case you need to read the data from localStorage and render the initial list. To save it to localStorage, again, you have to serialize the data. See the below snippets (link to working JSFIDDLE, because the below example does not work in the StackOverflow sandbox environment):
let ul = document.querySelector('ul');
let newItem = document.querySelector('input[type=text]');
const Store = {
serialize () {
return [].slice.call(document.querySelectorAll("li")).map(c => {
return {
text: c.textContent,
finished: c.querySelector("input").checked
}
})
},
get () {
return JSON.parse(localStorage.getItem("todos")) || []
},
save () {
return localStorage.setItem("todos", JSON.stringify(Store.serialize()))
}
}
const firstItems = Store.get()
firstItems.forEach(it => {
output(it.text, it.finished)
})
function output(v, finished) {
let newTodo = document.createElement('li');
newTodo.innerText = v || newItem.value;
newTodo.classList.add('todo');
let ulAppend = ul.append(newTodo);
ul.append(newTodo);
// Create a checkbox for each item
let checkbox = document.createElement('input');
if (finished) {
checkbox.checked = true
}
checkbox.setAttribute('type', 'checkbox');
let checkboxAppend = newTodo.append(checkbox);
newTodo.append(checkbox);
newItem.value = '';
}
let button = document.querySelector('.btn');
button.addEventListener('click', () => {
output()
Store.save()
});
ul.addEventListener('click', function(e) {
if (e.target.tagName === 'LI') {
e.target.remove();
} else if (e.target.tagName === 'INPUT') {
e.target.parentElement.classList.toggle('finished');
}
// Update the value in localStorage when you delete or add a new item
Store.save()
});
<ul></ul>
<input type="text" /> <button class="btn">Submit</button>
I have added the Store variable to simplify the way you get and set the data in localStorage.
The serialize method will read the TODOs from the list. document.querySelectorAll("li") returns a NodeList, but by doing [].slice.call(...) we convert it to an Array.

How to append data to localStorage item through onclick event?

I have a feature in my app wherein a user selects keywords and these keywords are displayed on a textfield once they are selected. If the page reloads, I want the keywords to remain and at the same time when the user selects more keywords, it will just be displayed along with the initial keywords.
I have checked out and tried this answer Append data to localStorage object but I get "keylocal.push is not a function" error.
if(localStorage.getItem('keywords') == null){
$('.words').on('click', function(e){
e.preventDefault();
keywords.push( $(this).data('word-name') );
document.getElementById('display').value = keywords
localStorage.setItem('keywords', keywords)
return keywords
console.log(keywords)
});
}
else{
var keylocal = localStorage.getItem('keywords')
document.getElementById('display').value = keylocal
$('.words').on('click', function(e){
keylocal.push( $(this).data('word-name') );
localStorage.setItem('keywords', keylocal)
var keyresult = localStorage.getItem('keywords')
console.log(keyresult)
document.getElementById('display').value = localStorage.getItem('keyresult')
return keywords
});
}
I expect to be able to display the previous keywords selected and the new keywords through onclick. However, it either only displays the new keywords or I get the .push is not a function error
try setting items on local storage using JSON.stringify and JSON.parse before pushing.
JSON.parse and JSON.stringify because Local storage only allows you to store string only.
sample working code
if(localStorage.getItem('keywords') == null){
$('.words').on('click', function(e){
e.preventDefault();
keywords.push( $(this).data('word-name') );
document.getElementById('display').value = keywords
localStorage.setItem('keywords', JSON.stringify(keywords)) // <- here
return keywords
console.log(keywords)
});
}
else{
var keylocal = JSON.parse(localStorage.getItem('keywords')) // <- here
document.getElementById('display').value = keylocal
$('.words').on('click', function(e){
keylocal.push( $(this).data('word-name') );
localStorage.setItem('keywords', JSON.stringify(keylocal)) // <- here
var keyresult = JSON.parse(localStorage.getItem('keywords')) // <- here
console.log(keyresult)
document.getElementById('display').value = JSON.parse(localStorage.getItem('keyresult'))
return keywords
});
}
First you need to get data from localStorage while onClick and append localStorage data with your data.

Persist cookie form values across multiple pages

The setting: I have a form that captures$thisSearch.val(), saves it as a cookie, and pushes to an array. The form is an overlay triggered from a menu item in the header so this can appear on any page in the site.
The issue is that it only seems to save/persist the input values on/from that page it was entered on. I'm trying to collect all these values into one list.items() array that can be entered anywhere in the site.
I've tried pushing the string to the array myself instead of the add function and moved the dom around for the search form.
I can update question when I know what to specifically ask. Any pointers / concepts I should be aware of for this would be great.
var cookieList = function(cookieName) {
var cookie = $.cookie(cookieName);
var items = cookie ? cookie.split(/,/) : new Array();
return {
"add": function(val) {
items.push(val);
$.cookie(cookieName, items.join(','));
},
"items": function() {
return items;
}
}
}
var list = new cookieList("PreviousSearches");
$searchSubmit.on('click', function() {
var $thisSearch = $(this).prev().find($searchInput);
if( $thisSearch.val() == '' ) {
alert('Please enter a search term');
console.log( list );
return false;
} else {
searchTerm = $thisSearch.val()
list.add( searchTerm );
}
});
var searchTerms = list.items();
var total = searchTermsFiltered;
var searchTermsFiltered = searchTerms.filter(Boolean).slice( - 5 ).reverse();
var searchtermClean = searchTermsFiltered.join();
$.each($(searchTermsFiltered), function(i,v){
if (!window.location.origin)
window.location.origin = window.location.protocol+"//"+window.location.host;
var lastURLRaw = window.location.origin+'/bch/?s='+v;
var lastURL = lastURLRaw.replace(/ /g, '+');
listItem = '<li>'+v+'</li>';
$('.tags, .search-tags').append(listItem );
});
I found the path specifier from jquerys $.cookie in this top answer below.
$.cookie(cookieName, items.join(',') , { path: '/' }); from my code.
why are my jquery cookies not available across multiple pages?

Categories

Resources