Hi I am a beginner web developer and am trying to build the interface of a simple e-commerce site as a personal project.The site has multiple pages with checkboxes.
When someone checks an element
it retrives the price of the element and
stores it in a variable.
But when I go to the next page and click on new checkboxes products the variable automaticly resets to its original state.
How can I save the value of that variable in Javascript?I am using the jQuery library.
EDIT:This is the code I've writen using sessionStorage but it still dosen't work when I move to next page the value is reseted.
How can I wright this code so that i dosen't reset on each page change.All pages on my website use the same script.
$(document).ready(function(){
var total = 0;
$('input.check').click(function(){
if($(this).attr('checked')){
var check = parseInt($(this).parent().children('span').text().substr(1 , 3));
total+=check;
sessionStorage.var_name=0 + total;
alert(sessionStorage.var_name);
}else{
var uncheck = parseInt($(this).parent().children('span').text().substr(1 , 3));
total-=uncheck;
}
})
The syntax for sessionStorage is simple, and it retains it's data until the browser window is closed. It acts exactly like any other javascript object. You can use dot-notation or square bracket notation (required for keys with spaces) to access stored values.
Storing values using sessionStorage
sessionStorage['value key'] = 'value to store';
Using stored values
alert(sessionStorage['value key']); // Alerts "value to store".
You could use localStorage to acomplish this. You'd need to set up a fallback for it, using localStorage however could be done like this:
Reading from storage:
if (localStorage['valueName'] !== undefined) {
input.value = localStorage['valueName'];
}
Writing to storage:
localStorage['valueName'] = input.value;
Here's a jsfiddle example: http://jsfiddle.net/yJjLe/
As already mentioned above you can use sessionStorage or localStorage. Another option available is HTML5 Web Databases
And take a look at this presentation.
Also keep in mind that html5 web storage is not secure as anyone can see your stored data simply from the console.
Related
I need some help.
I'm trying make it so that when I use text.splice() it keeps the changes when i reload the page.
Here is what I'm trying to do. It will Delete the item of the array that I wrote in the input element, but its not saving the changes made with splice().
function DeleteButton(){
const dltinpt = Deleteinput.value();
const index = secretPasswords.indexOf(dlinpt);
if (index > -1) {
secretPasswords.splice(index, 1);
}
}
Changes made to a value stored in a variable will not be persisted between page loads. That's just a fundamental principle of JavaScript and web browsers. If you want to preserve state between page loads you are going to need to use cookies or localStorage.
I'm trying to integrate this fiddle: http://jsfiddle.net/jaredwilli/ReT8n/ in a fiddle I'm doing:
https://jsfiddle.net/vlrprbttst/99c8gn7k/
Basically you have a basket with some items inside of it, you can add or remove them. What I want is that, on page refresh, the html() of the .basket is kept in local storage. I'm stuck here:
https://jsfiddle.net/vlrprbttst/z8cffk4c/
I've put the forLocalStorage variable in the click handler because otherwise, the var wouldn't update itself but now I'm guessing that the final local storage code
if(localStorage.getItem('toDoData')) {
forLocalStorage = localStorage.getItem('toDoData');
}
is not working because it can't retrive the variable?
I've tried moving around things but I'm stuck here. what am i doing wrong?
You need to update DOM once your variable is set, e.g:
// LOCAL STORAGEEEEEEEE
if (localStorage.getItem('toDoData')) {
forLocalStorage = localStorage.getItem('toDoData');
$('#cart').html(forLocalStorage);
itemsCount();
}
Local storage can only store string key value pairs. I ensured you are passing in a string and also added a function to populate the cart on refresh, which resolved problems.
function populateCart() {
var items = localStorage.getItem('toDoData') || '';
$('#cart').html(items);
}
Added this call inside document.ready, like so: -
$(document).ready(function() {
populateCart();
// rest of code
});
Working CodePen: http://codepen.io/owenayres/pen/oxKmZg
You can do some light reading here on local storage. It is, in my opinion, best practice to store the data for the HTML as some JSON in local storage, which you would then loop through and regenerate the HTML for when reading this data again.
I have a simple main menu program.
HOW IT WORKS:
Simple, once you click level one and click on the done button, it unlocks level two, the problem is when you refresh the page it does not save it and level two is gone again.
Code I've tried:
I tried HTML Local storage, here are some examples I used
window.highestLevel = localStorage.getItem('highestLevel');
and stuff like that but I can't get it to save the level.
Please help here is a link. jsFiddle
Note: I want to use html local storage.
Save it with
window.localStorage.setItem('highestLevel', window.higestLevel);
Make sure you check that the browser you are working with supports localstorage. You could use Modernizr or something to do that easily.
To set something in localstorage:
javascript
localStorage.setItem('your-identifier', your-data);
So for example, to save a user's name:
javascript
localStorage.setItem('username', 'Luke Skywalker');
To get "username" back from localstorage:
javascript
localStorage.getItem('username');
Hope this helps!
You'll need to use getItem (as you did in your question) when you load the page, and hide level 2 as needed:
if (localStorage.getItem("highestLevel") <= 1) {
$("#level2").hide();
}
You'll also need to setItem to save when the user gets to level 2:
function mainMenuLvl2() {
localStorage.setItem("highestLevel", 2)
$('#level2').show();
}
Here's a JSFiddle: http://jsfiddle.net/ptcbkamx/2/
You can use localStorage and sessionStorage to store your data on client side like below
localStorage.setItem("variablename","value"); //--> this value is object type anything
var storedValue = localStorage.getItem("variablename");
or
sessionStorage.setItem("variablename","value");
var storedValue = sessionStorage.getItem("variablename");
You can use:
localStorage.setItem("highestLevel", window.highestLevel);
Then, if you want to get the highest level, use this:
localStorage.getItem("highestLevel", window.highestLevel);
I hope this helped!
I have an <a> tag which I'm using to redirect the user to another xpage.
Its href property is:
<a target="_blank" href="http://serv/MyBase.nsf">
I use a simple view listing a doc. which contains the server and the name of the application.
So, I want to use some #DbLookup function in javascript to get into 2 var the above server and app name:
var server = #Unique(#DbColumn(#DbName(), "myVw", 1);
var name = #Unique(#DbColumn(#DbName(), "myVw", 2);
var concat = server+"/"+name;
return concat;
How can I compute the href property to return the concat variable?
Create a Link control xp:link and calculate the URL in attribute value:
<xp:this.value><![CDATA[#{javascript:var server .... }]]></xp:this.value>
Knut's approach is correct, but your code isn't :-). For every XPages load (or refresh) you do 4 #DbLookup. You can do a set of optimisations here:
Combine the result you want in the view itself, so you only need one lookup
Cache the value in the session (or application scope)
something like this (add nice error handling):
if (sessionScope.myHref) {
// Actually do nothing here
} else {
sessionScope.myHref = #Unique(#DbColumn(#DbName(), "myVw", 3);
}
return sessionScope.myHref;
The 3rd column would have the concatenation in the view already. That little snippet does a lookup only once per session. If it is the same for all users, use the applicationScope then it is even less.
I've been playing around with http://almende.github.com/chap-links-library/timeline.html which allows the user to add/edit/delete events on the timeline. Closing or refreshing the browser resets it to the pre-loaded data source - JSON, table info or Google Spreadsheet. Nothing the user adds or changes is saved.
How do you make user changes persistent?
I've used HTML5 localStorage before for saving text, checkbox, and select box entries, etc. but with this Timeline the only entry is:
div id="mytimeline"
which has a script associated with it:
// Instantiate our timeline object.
timeline = new links.Timeline(document.getElementById('mytimeline'));
which is the reference to the JS that builds the timeline container.
Any ideas or examples or pointers?
Thanks.
Update:
Here is what I have so far:
//Check to see if localStorage is supported
var db = getLocalStorage() || alert("Local Storage Not supported in this browser. Try updating to the latest Firefox, Chrome or Safari browsers.");
function getLocalStorage() {
try {
if(window.localStorage ) return window.localStorage;
}
catch (e)
{
return undefined;
}
}
//Store Timeline Data to localStorage
function storeTimelineData(){
var data=timeline.getData();
localStorage.setItem('mytimeline', JSON.stringify(data));
var storedData=JSON.parse( localStorage.getItem('myTimeline') );
// clear storage
function clearLocal() {
clear: localStorage.clear();
return false;
}
I've also made these changes - body onload="storedData()" to try to load localStorage saved values and changed div id="mytimeline" onmouseup="storeTimelineData()" to store the values when changes are made to the timeline.
Changes to the Timeline are being saved in localStorage and I can see these changes in the console for Key/Values. When I refresh the browser though, these are not being loaded into mytimeline. What did I miss?
Thanks.
I've never seen plugin until your post but in the API docs are all sorts of methods. The most important one you would need to start would be getData().
Simplest storage scenario would be to set up a timed interval to get the data , convert it to JSON and store it. Alternative would be to update your stored data every time use interacts with events.
A basic storage update function would be along the lines of:
function storeTimelineData(){
var data=timeline.getData();
localStorage.setItem('myTimeline', JSON.stringify(data));
}
Then when page loads you would need to check if there is data in localStorage , convert it to a javascript object using :
var storedData= JSON.parse( localStorage.getItem('myTimeline') );
And use this data to initialize the plugin if the data exists.
I have really just given you a basic overview. There are numerous details you will have to sort out from here