var btn = document.getElementById('insert'),
s = 0; //To increment the key(+1) each time the button is clicked and the user inputs the values so the first object's key is 1 then the second one is 2 and so on
btn.addEventListener('click', function() {
var ModelMake = prompt("Enter The Model Make"),
ModelYear = prompt("Enter The Model Year"),
Km = prompt("Enter The Amount Of Km"),
Price = prompt("Enter The Price"),
Status = prompt("Enter The Car's Status"),
table = document.getElementById('table');
var tableout = document.getElementById('tableout'),
FinalPrice,
Details;
localStorage.setItem(s += 1, JSON.stringify({
ModelMake: ModelMake,
ModelYear: ModelYear,
Km: Km,
Price: Price,
Status: Status,
FinalPrice: FinalPrice,
Details: Details
}));
This code inserts the following variables values(user inputs them) in a row and each value is in a column (cell), when i refresh the object IS stored in the localStorage even when i close my browser obviously but i want a way to keep it in the html whether i refresh or close the browser without having to extract it from the localStorage because i don't know how and it's not really what i want.
You could store your data in a cookie. Here is a tutorial that may be of use: Javascript and Cookies
If you want to do exactly, what you are asking I see few options for you:
on page load you can go thru all localStorage keys, find max number and assign it to S(Here is answer how to go thru all keys: Get HTML5 localStorage keys). I don't really like this way, but...
Store s value as separate key/value pair and extract it on page load
Related
The user fills out an input form with the number of pages and I want the user to be able to input the pages done (var pagesToBeSubtracted) and the function to subtract the pages and update it on the site.
function subtractPages() {
// Total pages that are grabbed from the input form
var totalPages = document.getElementById("numPages").value;
//Value of the input type number for done pages
var pagesToBeSubtracted = document.getElementById("donePages").value;
var remainingPages;
remainingPages = totalPages - pagesToBeSubtracted;
//Updating the number on the actual website
document.getElementById("pagesLeft").innerHTML = remainingPages;
However if you have total pages at 100 and you put that you did 5 pages it will go to 95 but if you press it again it will stay the same, if you bump it to 10 it will go down to 90 etc...
I get I should somehow save the result so that the next time the function is called, it doesn't start from the original number every time but from the updated one. But I can't figure out how to do it since I set the variable for total pages from the input form and every time the function is called it sets it at the same number again.
I'm sure I'm missing something elementary but I can't figure it out.
Once your user submit value in the input form, you can use localStorage to save that value. You can then access that value on user revisit to your website. localStorage store data locally within the user's browser. The data will not be deleted when the browser/computer is closed.
You can store a value by using setItem method of localStorage:
localStorage.setItem("totalPages", numberOfTotalPages);
localStorage.setItem("pagesToBeSubtracted", numberOfPagesToBeSubtracted);
You can get a stored value by using getItem method of localStorage
document.getElementById("pagesLeft").innerHTML = localStorage.getItem("totalPages")-localStorage.getItem("pagesToBeSubtracted");
For anyone that might be looking for the same solution, #Turnip did it I'm just copying and pasting his jsfiddle so that anyone next that comes can just see it.
https://jsfiddle.net/1n36wyf2/
var remainingPages = document.getElementById("numPages").value;
document.getElementById("btnSubtract").addEventListener("click", subtractPages);
// Update `remainingPages` when `#numPages` changes.
document.getElementById("numPages").addEventListener("input", function() {
remainingPages = this.value;
});
function subtractPages() {
var pagesToBeSubtracted = document.getElementById("donePages").value;
remainingPages = remainingPages - pagesToBeSubtracted;
//Updating the number on the actual website
document.getElementById("pagesLeft").innerHTML = remainingPages;
}
I am trying to pull a URL for an image in storage that is currently logged in the firebase real time database.
This is for a game of snap - there will be two cards on the screen (left image and right image) and when the two matches the user will click snap.
All of my image urls are stored in the following way:
Each one has a unique child called "index" - I also have another tree that is just a running count of each image record. So currently I am running a function that checks the total of the current count, then performs a random function to generate a random number, then performs a database query on the images tree using orderByChild and an equalTo that contains the random index number.
If I log the datasnap of this I can see a full node for one record (So index, score, url, user and their values) however if I try to just pull the URL I get returned a value of Null. I can, rather annoyingly, return the term "URL" seemingly at my leisure but I can't get the underlying value. I've wondered if this is due to it being a string and not a numeric but I can't find anything to suggest that is a problem.
Please bare in mind I've only been learning Javascript for about a week at max, so if I'm making obvious rookie errors that's probably why!
Below is a code snippet to show you what I mean:
var indRef = firebase.database().ref('index')
var imgRef = firebase.database().ref('images')
var leftImg = document.getElementById('leftImg')
var rightImg = document.getElementById('rightImg')
document.addEventListener('DOMContentLoaded', function(){
indRef.once('value')
.then(function(snapShot){
var indMax = snapShot.val()
return indMax;
})
.then(function(indMax){
var leftInd = Math.floor(Math.random()* indMax + 1)
imgRef.orderByChild('index').equalTo(leftInd).once('value', function(imageSnap){
var image = imageSnap.child('url').val();
leftImg.src=image;
})
})
})
When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.
Your code needs to cater for that list, by looping over Snapshot.forEach():
imgRef.orderByChild('index').equalTo(leftInd).once('value', function(imageSnap){
imageSnap.forEach(function(child) {
var image = child.child('url').val();
leftImg.src=image;
})
})
I have been trying to code in javascript where I want input given to be displayed on screen. I want to store the data from input in LocalStorage. I tried to take the value and using localStorage.setItem and localStorage.getItem I stored in local storage too. But as I want to display all the records I have inserted every time submit button has been clicked, I want to store current and previous records too.
I tried to push into an array but it had only current records and not previously stored values. I don't want jquery. I just want simple javascript code.
thank you.
eg-
var data=[];
function myFunction(data)
{
var name= document.getElementById("nm").value;
localStorage.name= name;
for(var i=0;i<localStorage.length;i++)
{
var key = localStorage.key(i);
var value = localStorage.getItem(key);
data.push( value);
}
}
Yep, as mentioned in the comments it is best to just store the String representation of your array and store it as a value in localstorage. Web localstorage lets you store simple key value pairs which can be integers or strings (mostly strings) official docs
You could do something like this:
var name= document.getElementById("nm").value;
var data;
if (localStorage.getItem("name") === null)
//First value to be stored
data = [];
else
//There is some value already in the array
data = JSON.parse(localStorage.getItem("name"));
//Push name to data array in any case
data.push(name);
//Update localStorage
localStorage.setItem("name",JSON.stringify(data));
I hope this gets you started in the right direction.
I have list of students like as follows form from user input form:
//student form input for 1st time
var student={name:"a",roll:"9",age:13}
//student form input for 2nd time
var student={name:"b",roll:"10",age:14}
//student form input for 3rd time
var student={name:"c",roll:"11",age:15}
Actually, i am developing phonegap applications. Each time the user submit form-input i.e. student information, I want to save them into localstorage. Finally, when online, i want to sync them. I know i can store them in localstorage as follows:
localStorage.setItem("studentinfo", JSON.Stringfy(student));
But, this will remove the first student info in the local storage when i save second student info.
Infact, when i save first, second and third input respectively, i want to add them in localstorage array and finally the result in localstorage should be like
key=studentlist,
value=[
{name:"a",roll:"9",age:13},
{name:"b",roll:"10",age:14},
{name:"c",roll:"11",age:15}
]
How can it be done in localstorage or phonegap localstorage?
You want to hold all your students in an array like this:
var students = [];
students.push({name:"a",roll:"9",age:13});
students.push({name:"b",roll:"10",age:14});
students.push({name:"c",roll:"11",age:15});
And then store that in localStorage:
localStorage.setItem('studentsInfo', JSON.stringify(students));
The best way to do that would be with a function like this:
// When you get more student information, you should:
var addNewStudent = function (name, roll, age) {
// retrieve it (Or create a blank array if there isn't any info saved yet),
var students = JSON.parse(localStorage.getItem('studentsInfo')) || [];
// add to it,
students.push({name: name, roll: roll, age: age});
// then put it back.
localStorage.setItem('studentsInfo', JSON.stringify(students));
}
I want a user to key in an ID Number. When the user clicks on a button, the code will look for an array that has a list of all the id numbers to check if it exists. It will then go to check the price of that id number. Based on the price and what ID number was looked up I want this to change a variable called 'cost' dynamically. So for example, a user keys in the number "5555" The code looks up if the ID 5555 exists, if it does, it checks the price of that id. Based on that price, I want it to change a variable called cost. Likewise, if I looked up an id of "1234". It would look up the id, if it existed, got the price and then changed the variable called cost.
I don't even know where to begin with this. I was thinking about using arrays to map the id numbers and price but I don't know if that will work. I want a number to equal another number essentially and then change a variable based on the second number and I can't think of how to do that.
id[0] = new Array(2)
id[1] = "5555";
id[2] = "6789";
price = new Array(2)
price[0] = 45;
price[1] = 18;
You could use an object as a dictionary like object.
// Default val for cost
var cost = -1;
// Create your dictionary (key/value pairs)
// "key": value (e.g. The key "5555" maps to the value '45')
var list = {
"5555": 45,
"6789": 18
};
// jQuery click event wiring (not relevant to the question)
$("#yourButton").click(function() {
// Get the value of the input field with the id 'yourInput' (this is done with jQuery)
var input = $("#yourInput").val();
// If the list has a key that matches what the user typed,
// set `cost` to its value, otherwise, set it to negative one.
// This is shorthand syntax. See below for its equivalent
cost = list[input] || -1;
// Above is equivalent to
/*
if (list[input])
cost = list[input];
else
cost = -1;
*/
// Log the value of cost to the console
console.log(cost);
});