How to keep input and page the same using local storage - javascript

Hi I wrote a code which has a working search with filters applied to it. The only problem I am having is that it doesn't stay the same as to how the filters where set when the user closes or refreshes the webpage. I am not using a checkbox
This is my code so far
saveTask: function(name, isCompleted) {
window.localStorage.setItem(name, isCompleted);
},
renderTasks: function() {
for (var i = 0; i < window.localStorage.length; i++) {
var taskName = window.localStorage.key(i);
var isCompleted = window.localStorage.getItem(taskName) == "true";
var taskHTML = Todo.template.replace("<!-- TASK_NAME -->", taskName);
if (!isCompleted) {
Todo.container.insertAdjacentHTML('afterbegin', taskHTML);
}
}
}
This is a js fiddle https://jsfiddle.net/4p8awnqx/6/
I am trying to keep the filters the same using local storage so that when it is closed or refreshed it stays the same

Related

How can I save a visual change a user made to my web page?

So I'm making a web page where users can press buttons to add elements using appendChild but when they refresh the page it all goes away. Is there something I can do to save what the users add to the page so that when they refresh it it stays the same?
HTML:
<input type="text" id="input" placeholder="write anything here...">
<button id="submit" onclick="createEl()">Submit</button>
<div class="text-div" id="text-div"></div>
CSS:
#input {
width: 500px;
height: 50px;
padding-left: 5px;
}
#submit {
height: 55px;
}
JAVASCRIPT:
var txtDiv = document.getElementById("text-div")
var inputField = document.getElementById("input")
function createEl() {
if (inputField.value !== "") {
var p = document.createElement("p")
var pNode = document.createTextNode(inputField.value)
p.appendChild(pNode)
txtDiv.appendChild(p)
}
}
In the absence of a database, you could try storing their progress within window.localStorage. On page load, you would need to run a function that checks for this item; if present, the function would then repopulate all of their information. After each submission, you would also need to update local storage so that their progress stays current.
Well, as people said earlier the if you want to load your data in all browsers regardless of where did those data came from, you should set up a database, based on your need and specification. Otherwise, you can get used to existing stuff in browsers such as localStorage. So you need to create a property in it, then on each page reload check whether there are data saved there or not with onload event.
So your final code should be something like this:
var txtDiv = document.getElementById("text-div")
var inputField = document.getElementById("input")
var items = [];
function createItem(item) {
var p = document.createElement("p")
var pNode = document.createTextNode(item)
p.appendChild(pNode)
txtDiv.appendChild(p)
}
window.onload = function() {
if (window.localStorage.getItem("items") !== null) {
items = JSON.parse(window.localStorage.getItem("items"))
var itemsLength = items.length
for (var i = 0; i < itemsLength; i++) {
createItem(items[i])
}
}
}
function createEl() {
if (inputField.value !== "") {
createItem(inputField.value)
items.push(inputField.value)
window.localStorage.setItem("items", JSON.stringify(items))
}
}
You will need to use some method of persistent storage. If you don't care about saving the changes forever, then you can save user changes in localStorage. If you need to make sure the changes will always be available, then you'll need to create a database and handle saving and loading data from an API that connects to it.
Here's an example of how to do this using localStorage:
var txtDiv = document.getElementById("text-div")
var inputField = document.getElementById("input")
const getSaved = () => JSON.parse(localStorage.getItem("saved"));
function saveEl(val) {
const saved = getSaved();
let newInputArr = saved ? [...saved, val] : [val];
localStorage.setItem("saved", JSON.stringify(newInputArr));
}
function createEl(val) {
var p = document.createElement("p")
var pNode = document.createTextNode(val)
p.appendChild(pNode)
txtDiv.appendChild(p)
}
function saveAndCreate() {
if((inputField.value !== "")) {
saveEl(inputField.value);
createEl(inputField.value);
}
}
const saved = getSaved();
if(saved && saved.length) {
saved.forEach((val) => {
createEl(val)
})
}

`How to change between list view and grid view and also keep the current state after page refresh

I need to toggle between list view and grid view which i was able to do using js to change the css but the problem is if a user refresh the page the default view is restored, how can I make this, probably append the view name to the url so that the current view will remain after user refresh page. example having the following URl www.example.com/item/search?q=myquery&style=list, www.example.com/item/search?q=myquery&style=grid, or is there a better way to do this. below is a fiddle of my code and any refresh will return the view to grid even when i select list view
JS FIDDLE
Note: I'm using yii2 framework so regarding the url formation i'm open to both php and JS solution, thanks in advance
$(".listView").on('click', function() {
listView();
});
$(".gridView").on('click', function() {
gridView();
});
// Get the elements with class="column"
var elements = document.getElementsByClassName("column");
// Declare a loop variable
var i;
// List View
function listView() {
for (i = 0; i < elements.length; i++) {
elements[i].style.width = "100%";
}
}
// Grid View
function gridView() {
for (i = 0; i < elements.length; i++) {
elements[i].style.width = "50%";
}
}
var container = document.getElementById("btnContainer");
var btns = container.getElementsByClassName("btn");
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener("click", function() {
var current = document.getElementsByClassName("active");
current[0].className = current[0].className.replace(" active", "");
this.className += " active";
});
}
In order to do what you want, actually you dun need to do any work on backend but simply using the cookie.
You may improve it, I just provide a picture.
$(".listView").on('click', function() {
listView();
setCookie('list');
});
$(".gridView").on('click', function() {
gridView();
setCookie('grid');
});
function setCookie(name) {
document.cookie = name;
}
And when you start the JS, check the cookie first by
var x = document.cookie;
if (x == 'list'){...}
else if (x == 'grid'){...}
You may also choose to use localStorage, the technical is the same. However, only when if you list and grid data has no difference, and no server data is further required.
I think MatrixTai has the right idea, but I personally prefer usually localStorage.
Here is an example with a functions for getting/setting the view:
$(".listView").on('click', function() {
listView();
setView('list');
});
$(".gridView").on('click', function() {
gridView();
setView('grid');
});
function setView(view) {
localStorage.setItem('view', view);
}
function getView(view) {
return localStorage.getItem('view');
}

Function stops working after retrieving localStorage

I'm using localStorage on two lists, fruit-shelf & fruit-basket.
If you click on a fruit from fruit-shelf, it appends it to the fruit-basket, and if you refresh the page it's still there — so it remembers everything as it should.
Problem is: if you add one fruit, and then refresh page, you can't add more fruits, the program completely stops working.
I've added a Clear Local Storage button, which works. If you click on it and refresh page, you can add fruits again. But as soon as one fruit is added and you refresh page, you can't add more items to the fruit-basket.
I'm not sure how to put a name on the problem so it's hard to search for solutions (I've tried!).
Can someone point me in the right direction? :-)
Fiddle (I couldn't use SO Snippet here because of localStorage):
https://jsfiddle.net/nrv269hc/7/
JS:
(function() {
var btnClearStorage = document.querySelector('.btn-delete-all');
var fruitShelf = document.querySelector('.fruit-shelf');
var fruitShelfItems = document.querySelectorAll('.fruit-shelf li');
var fruitBasket = document.querySelector('.fruit-basket');
// Store current state of fruitSheflf & fruitBasket
function storestate() {
localStorage.fruitShelf = fruitShelf.innerHTML;
localStorage.currentFruitBasket = fruitBasket.innerHTML;
};
function retrievestate() {
// Retrieve fruits left from shelf
if (localStorage.fruitShelf) {
fruitShelf.innerHTML = localStorage.fruitShelf;
}
// Retrieve stored fruits
if (localStorage.currentFruitBasket) {
fruitBasket.innerHTML = localStorage.currentFruitBasket;
}
};
retrievestate();
for (var i = 0; i < fruitShelfItems.length; i++) {
fruitShelfItems[i].addEventListener('click', function(event) {
fruitBasket.appendChild(this);
storestate();
});
}
// Clear Local Storage
btnClearStorage.addEventListener('click', function() {
localStorage.clear(fruitShelf);
localStorage.clear(fruitBasket);
});
})();
You need to update the fruitShelfItems as the HTML is update after retrievestate.
Look at updated JsFiddle
(function() {
var btnClearStorage = document.querySelector('.btn-delete-all');
var fruitShelf = document.querySelector('.fruit-shelf');
var fruitShelfItems = document.querySelectorAll('.fruit-shelf li');
var fruitBasket = document.querySelector('.fruit-basket');
// Store current state of fruitSheflf & fruitBasket
function storestate() {
localStorage.fruitShelf = fruitShelf.innerHTML;
localStorage.currentFruitBasket = fruitBasket.innerHTML;
};
function retrievestate() {
// Retrieve fruits left from shelf
if (localStorage.fruitShelf) {
fruitShelf.innerHTML = localStorage.fruitShelf;
}
// Retrieve fruit basket
if (localStorage.currentFruitBasket) {
fruitBasket.innerHTML = localStorage.currentFruitBasket;
}
// you need to update the fruitShelfItems as the HTML is update after retrievestate
fruitShelfItems = document.querySelectorAll('.fruit-shelf li');
};
retrievestate();
for (var i = 0; i < fruitShelfItems.length; i++) {
fruitShelfItems[i].addEventListener('click', function(event) {
fruitBasket.appendChild(this);
storestate();
});
}
// Clear Local Storage
btnClearStorage.addEventListener('click', function() {
localStorage.clear(fruitShelf);
localStorage.clear(fruitBasket);
});
})();

How to populate jqGrid filter toolbar and search when the page loads (ASP.net webforms)

Currently, I'm trying to populate the filterToolbar with values taken in from a cookie. If there is cookie data for the filters, I want it to fill the respective textboxes and filter the jqGrid for that data.
I'm using ASP.net webforms, so most of my data is initialized already. How/where could I add javascript in order to get this going?
I actually figured out what I was doing.
So what I ended up doing as a solution was adding a timeout function in the document.ready function
$(document).ready(function () {
// some code
setTimeout(function () {
$('#Jqgrid1')[0].triggerToolbar();
}, 500)
//some code
}
My guess is that I couldn't use the $('#grid')[0].toggleToolbar() to force it because whenever I tried to use it, it was before the whole grid was finish setting up.
In the ASP webform, I had several functions registered.
<cc1:JQGrid ID="Jqgrid1" runat="server"
Height="630"
SearchDialogSettings-Draggable="true"
EnableViewState="false"
AutoWidth="True" >
<ClientSideEvents
LoadComplete="Jqgrid1_LoadComplete"
GridInitialized="initGrid"
/>
<%-- grid code --%>
</cc1:JQGrid>
The LoadComplete is executed after the grid is loaded. I tried doing triggering my toolbar there, but didn't work. My guess is, again, it was too early in the grid execution to use the triggerToolbar() function.
The same went for the GridInitialized events (even though both events would seem to imply to me that the grid is done doing its thing... but whatever...)
The way that I read my cookies in was actually in the GridInitialized event handler.
function initGrid() {
var myJqGrid = $(this);
var valueName = 'GridFilters';
var myCookie = document.cookie;
var gridFilterString;
var gridFilterArray;
var currentFilter;
var myCookie_arr;
var myDic = {};
if (myCookie.indexOf(valueName) > -1) { // don't even bother if the cookie isn't there...
myCookie_arr = myCookie.split("; "); // looking for the cookie I need
// read cookies into an array
for (var i = 0; i < myCookie_arr.length; i++)
{
parts = myCookie_arr[i].split("=");
first = parts.shift(); // remove cookie name
myDic[first.trim()] = parts.join("=").trim(); // handles multiple equality expressions in one cookie
}
if (myDic.hasOwnProperty("GridFilters"))
gridFilterString = myDic["GridFilters"];
if (gridFilterString != "NONE") {
myFiltersDic = {}
myFiltersArr = gridFilterString.split("&")
for (var i = 0; i < myFiltersArr.length; i++) {
parts = myFiltersArr[i].split("=");
myFiltersDic[parts[0].trim()] = parts[1].trim();
}
myParams = $(this).jqGrid("getGridParam", "postData");
var filters = []
for (keys in myFiltersDic) {
$('#gs_' + keys.trim()).val(myFiltersDic[keys].trim());
}
$.cookie('m_blnSearchIsHidden', "0", "/");
if (!isLoaded)
{
$(this)[0].toggleToolbar();
}
isLoaded = true;
}
}
}

JS cookies refresh itself when the page refreshes

I need to use cookies for my new webshop, so if the page refreshes the old values will stay in.
Now i've created my cookies, and it works perfectly fine, but when I'm refreshing the page, the cookie goes empty again. If i'm going to a different page, the cookie stays (path:/)
Now i'm confused and need someone to clarify what i'm doing wrong right here, so I came here to ask my question!
Here is the code im using
$.cookie.raw = true;
$.cookie.json = true;
$.cookie('cart', unescape);
function UpdateTotals() {
TotalPrice = 0;
for (var i = 0; i < Orders.length ; i++) {
var SearchResult = SubMenuItems.filter(function(v) {
return v.submenu_id === Orders[i];
})[0];
TotalPrice += parseFloat(SearchResult.price);
$.cookie('cart', JSON.stringify(Orders), { expires: 7, path: '/' });
Now if I click on some orders, the cookies stays filled with the jSon values.

Categories

Resources