Store users choice data in my array temporarily - javascript

This is my form and below is a function. I need 3 functions, 1 to store data, 1 to save the data and 1 to show all stored data. How can I do all of these functions so they all correspond with each other.
NOTE: The user will be entering the data so it's the users choice data which would temporarily be saved. The user should be able to click on the buttons to function the function but how can I do the three functions properly.
<form name = "Music">
<p>Input a Song Name, Artist, Collaborations, Duration or Album</p>
<input type="text" name = "Song_Name" id= "Song_Name" size="20"> <br>
<input type="text" name = "Artist" id= "Artist" size="20"> <br>
<input type="text" name = "Collaborations" id= "Collaborations" size="20"> <br>
<input type="text" name = "Duration" id= "Duration" size="20"> <br>
<input type="text" name = "Album" id= "Album" size="20"> <br>
<input type="button" value = "Save" onclick = "Save()"> <br>
<input type="button" value = "Search" onclick = "Store()"> <br>
<input type="button" value = "Show_All" onclick = "Show_All()"> <br>
Save function:
var catalogue[];
function Save = Music.Song_Name.Artist.Collaborations.Duration.Album.Save{
var SongName = document.getElementById('Song_Name').value;
var Artist = document.getElementById('Artist').value;
var Collaborations = document.getElementById('Collaborations').value;
var Duration = document.getElementById('Duration').value;
var Album = document.getElementById('Album').value;
document.write("You have chosen "+ Song_Name + Artist + Collaborations + Duration + Album)
}

First, I would recommend storing the values in an object rather than an array. It's much easier to work with when you have multiple, related pieces of data. Here's how it would work for Store and Show:
var catalogue;
function Store() {
catalogue = {
SongName: document.getElementById('Song_Name').value;
Artist: document.getElementById('Artist').value;
Collaborations: document.getElementById('Collaborations').value;
Duration: document.getElementById('Duration').value;
Album: document.getElementById('Album').value;
}
}
function Show_All() {
document.getElementById('Song_Name').value = catalogue.SongName;
document.getElementById('Artist').value = catalogue.Artist;
document.getElementById('Collaborations').value = catalogue.Collaborations;
document.getElementById('Duration').value = catalogue.Duration;
document.getElementById('Album').value = catalogue.Album;
}
How you handle the "Save" would depend on where you want to save it to, but the general idea would be that you would pass the catalogue value either directly into wherever you're saving it, or parse the properties of the catalogue object and pass each one in to wherever you're saving them.

Related

Appending Value to LocalStorage

I want to add new values to localStorage for my Pizza website in which I want the admin to be able to add pizzas. I have this code:
function store() {
var inputName = document.getElementById("name");
localStorage.setItem("name", inputName.value);
var inputDescription = document.getElementById("description");
localStorage.setItem("description", inputDescription.value);
var inputPrice = document.getElementById("price");
localStorage.setItem("price", inputPrice.value);
}
<form onsubmit="store()" id="form1">
<label for="name">Namn:</label><br>
<input class="name" type="text" id="name" name="name" placeholder="Skriv här..."><br>
<label for="description">Beskrivning:</label><br>
<input class="description" type="text" id="description" name="description" placeholder="Skriv här...">
<br>
<label for="price">Pris:</label><br>
<input class="margin-bot" type="text" id="price" name="price" placeholder="Skriv här...">
<br>
<br>
<button form="form1" class="submit-button" type="submit">Lägg Till</button>
</form>
How do I add new pizzas for each time? Everytime I try to add a new value it just replaces the existing one.
function store() {
let inputName = document.getElementById("name");
let inputDescription = document.getElementById("description");
let inputPrice = document.getElementById("price");
let pizzas = []
if(localStorage.getItem("pizzas")){
pizzas = JSON.parse(localStorage.getItem("pizzas"));
}
let pizza = {}
pizza.name = inputName.value;
pizza.description = inputDescription.value;
pizza.price = inputPrice.value;
pizzas.push(pizza)
localStorage.setItem("pizzas", JSON.stringify(pizzas))
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form onsubmit="store()" id="form1">
<label for="name">Namn:</label><br>
<input class="name" type="text" id="name" name="name" placeholder="Skriv här..."><br>
<label for="description">Beskrivning:</label><br>
<input class="description" type="text" id="description" name="description" placeholder="Skriv här...">
<br>
<label for="price">Pris:</label><br>
<input class="margin-bot" type="text" id="price" name="price" placeholder="Skriv här...">
<br>
<br>
<button form="form1" class="submit-button" type="submit">Lägg Till</button>
</form>
</body>
</html>
This should help, first I check the localStorage some pizza is already stored in there or not, if there, then I take that parse it and add one more pizza to it from the form input, if not I create a completely new array and then add the value from the form input then store it in the localStorage.
first it would be better to replace your code to use "objects & arrays" instead of "string variables", like this example i made for you:
function store() {
var inputName = document.getElementById("name");
var inputDescription = document.getElementById("description");
var inputPrice = document.getElementById("price");
return ({
name: inputName.value,
description: inputDescription.value,
price: inputPrice.value
});
}
function updateStore(key = 'pizzas'){
let pizzasArray = JSON.parse(localStorage.get(key)) || [];
pizzasArray.push(store());
localStorage.setItem(key, JSON.stringify(pizzasArray));
}
You can keep it as json array in local storage.For Example;
function addStoreForArray(key, value) {
var storeArrayObj = localStorage.getItem(key);
if(storeArrayObj){
storeArrayObj = JSON.parse(storeArrayObj);
storeArrayObj.push(value);
} else {
storeArrayObj = [];
storeArrayObj.push(value);
}
localStorage.setItem(key, JSON.stringify(storeArrayObj));
}
addStoreForArray('pizzas', {name:'pizzaName', description: 'pizzaDescription', price: 10});
You can create an array to store many pizzas and to check if already exists you can call the getStorage() function and if storagePizzas includes your new pizza then update the value
arrayOfPizzas = []
function storeArray() {
let pizzaCreated = {}
pizzaCreated.name = document.getElementById("name").value;
pizzaCreated.description = document.getElementById("description").value;
pizzaCreated.price = document.getElementById("price").value;
let storageItems = getStorage();
// Check ...
arrayOfPizzas.push(pizzaCreated);
setStorage(arrayOfPizzas);
}
function setStorage(arr){
localStorage.setItem('arrayOfPizzas', JSON.stringify(arr));
}
function getStorage(){
return JSON.parse(localStorage.getItem('arrayOfPizzas');
}
You need to store the pizzas the user has created in an array. You can store the array in local storage, you just need to make sure you can serialize and deserialize it properly
Take the values from the input field
Grab your array of pizzas from local storage
If the array doesn't exist yet, getItem will return null, so you can give it an array to start off with.
Add the new pizza to the array
Save the pizzas array in local storage again.
function store() {
var newPizza = {
name: inputName.value,
description: inputDescription.value,
price: inputPrice.value
}
var pizzas = localStorage.getItem('pizzas')
if (!pizzas) {
pizzas = []
} else {
pizzas = JSON.parse(pizzas)
}
pizzas.push(newPizza)
localStorage.setItem('pizzas', JSON.stringify(pizzas))
}

Updating a localStorage Item Using JavaScript/jQuery?

I am sorry to keep asking this question but I am really struggling with it and I cannot figure out what is going wrong, I have read countless SO pages and general internet searches with no luck. A few people have helped me on here but the values are updating incorrectly so I thought it would be best to ask a fresh question with my most recent trials.
The challenge is to create a client-side (only) mock dog walking application based on localStorage, I so far am able to add, delete, and view appointments in the browser. I also have an edit function set up, however when I hit submit (#edit), the value at position [x] (end index) updates no matter which index I try to edit. Here is an example of my stored arrays in localStorage under key 'bookings':
[0]{fname: "John", lname: "Smith"}
[1]{fname: "Jane", lname: "Doe"}
[2]{fname: "David", lname: "Miller"}
When I hit edit on John Smith, for example, it will replace the values of David Miller, rather than Johns details. I thought of trying to find the index of each person similar to what I have done when finiding the values to display in HTML (bookings[i].lname), however this throws an error saying that i cannot be used before initialisation (makes sense, but not sure how to work around it).
Here is my most recent JS:
// ~~~ add bookings to localStorage
var bookings = JSON.parse(localStorage.getItem("bookings")) || [];
window.onload = showBooking();
$("#submit").click(function() {
var newBookings = {
fname: $('#fname').val(),
lname: $('#lname').val()
}
bookings.push(newBookings);
var json = JSON.stringify(bookings);
window.localStorage.setItem("bookings", json);
showBooking();
});
// ~~~ edit bookings in localStorage
$(document).on('click','#edit',function (e) {
e.preventDefault();
var parent_form = $(this.form);
var fname = parent_form.find('.input:eq(0)').val();
var lname = parent_form.find('.input:eq(1)').val();
const i = bookings.findIndex(booking => bookings.fname == fname && bookings.lname == lname);
deleteBooking(i);
bookings.push({
fname,
lname
});
var json = JSON.stringify(bookings);
window.localStorage.setItem("bookings", json);
// showBooking();
});
// ~~~ display bookings in browser
function showBooking() {
var bookingResult = document.getElementById("result");
var ul = document.createElement("ul");
bookingResult.innerHTML = "";
for (let i = 0; i < bookings.length; i++) {
bookingResult.innerHTML += `<div class="card card-body bg-light m-4">
<h3>${bookings[i].fname + " " + bookings[i].lname}
<button onclick="deleteBooking(${i})" class="btn btn-danger text-light ">Delete</button>
<button onclick="editBooking(${i})" class="btn btn-danger text-light ">Edit</button>
</h3>
</div>`;
}
}
// ~~~ edit bookings in browser
function editBooking(i) {
// $('#regForm').hide();
$('#result').hide();
var currentItem = document.getElementById("currentItem");
var editBooking = document.getElementById("editAppt");
currentItem.innerHTML += `<div class="card card-body bg-light m-4">
<h3>${bookings[i].fname + " " + bookings[i].lname} </h3>
</div>`;
editBooking.innerHTML = `<input type="text" class="input" id="fname_${i}" placeholder="${bookings[i].fname}" name="${bookings[i].fname}" value="${bookings[i].fname}" required>
<input type="text" class="input" id="lname_${i}" placeholder="${bookings[i].lname}" name="${bookings[i].lname}" value="${bookings[i].lname}" required>
<input id="edit" type="submit" value="Edit">`;
}
// ~~~ delete bookings from localStorage
function deleteBooking(i) {
bookings.splice(i, 1);
localStorage.setItem("bookings", JSON.stringify(bookings));
showBooking();
}
My form for creating an appointment (this changes when editBooking is called):
<form id="regForm" name="regForm" action="" class="col-sm-6">
<div id="editAppt" class="row">
<input type="text" class="input" id="fname" placeholder="First Name" name="fname" required>
<input type="text" class="input" id="lname"placeholder="Last Name" name="lname" required>
<input id="submit" type="submit" value="Submit">
</div>
</form>
You need to assign a unique identifier to each appointment. This will help fix your problem as you are currently identifying appointments by their first name, last name and position in the array.
When you edit an appointment, it removes it from its current position and adds it at the end which changes the index of all the current elements leading to your problem.
This would also cause problems if you had two appointments with the same name.
For a unique identifier, I suggest using new Date().getTime() for now.
var newBookings = {
id: new Date().getTime(),
fname: $('#fname').val(),
lname: $('#lname').val()
}
Once you've assigned a unique identifier to each appointment, you can change your Edit button so that it looks like this:
<input data-id="${bookings[i].id}" id="edit" type="submit" value="Edit">
Then in your Edit event handler, change the bottom part so that it looks like this:
let i = bookings.findIndex(booking => booking.id == $(this).data("id"));
bookings[i].fname = fname;
bookings[i].lname = lname;
var json = JSON.stringify(bookings);
window.localStorage.setItem("bookings", json);
So to explain, assign a unique identifier to each appointment, store the id in the data-id attribute, retrieve the data-id, find the index of the appointment with that id, update the appointment properties, save the bookings.
If you also want to improve the readability of your code, I suggest not mixing vanilla JavaScript and jQuery, i.e. document.getElementById("result") could be $("#result")

How to store inputs multiple times into local storage

I am currently inputting values into local storage like this
<form name="myform" action="" method="GET">
Event Name: <INPUT TYPE="text" NAME="name" VALUE="" id="input1"><br />
Event Date and Time: <INPUT TYPE="datetime-local" NAME="date" Value="" id="input2"><br />
Event Location: <INPUT TYPE="text" NAME="location" VALUE="" id="input3"><br />
Event Notes: <INPUT TYPE="text" NAME="notes" VALUE="" id="input4"><br />
<button onclick="storeValues(event)" type=submit>Submit</button>
</form>
<script>
function storeValues(e) {
e.preventDefault();
let storedEvents = JSON.parse(localStorage.getItem("Events")) || [];
const newEventDetails = {
name: document.getElementById('input1').value,
dateTime: document.getElementById('input2').value,
location: document.getElementById('input3').value,
notes: document.getElementById('input4').value
}
storedEvents.push(newEventDetails);
localStorage.setItem("Events", JSON.stringify(storedEvents));
console.log('storedEvents', storedEvents);
}
</script>
However I found that I was unable to Output more than 1 value from local storage which I am currently achieving doing this.
<h2 class="title">Upcoming Events</h2>
<h3 id='input1'> </h3>
<h3 id='input2'> </h3>
<h3 id='input3'> </h3>
<h3 id='input4'> </h3>
<!-- running script here will populate H2's with values from local storage -->
<script>
document.getElementById('input1').innerText = localStorage.getItem('EventName');
document.getElementById('input2').innerText = localStorage.getItem("EventDateAndTime");
document.getElementById('input3').innerText = localStorage.getItem("EventLocation");
document.getElementById('input4').innerText = localStorage.getItem("EventNotes");
</script>
How would I be able to display the most recent input using those fields and then display ALL previous inputs on another page?
Your current code won't work, because you're retrieving items from EventName, EventDateAndTime, etc properties of local storage, but you never save to those properties, so they'll be null.
You're storing all the event info in a single property, localStorage.Events, which contains an array that you push to when you add a new event. So, to display the last item saved, you just need to access the top item in the array, and to display previous items saved, just access the appropriate previous index in the array:
const renderEvent = (event) => {
document.getElementById('input1').textContent = event.name;
document.getElementById('input2').textContent = event.dateTime;
document.getElementById('input3').textContent = event.location;
document.getElementById('input4').textContent = event.notes;
};
// Display last event:
const storedEvents = JSON.parse(localStorage.getItem("Events"));
if (!storedEvents) throw new Error('No events');
const lastEvent = storedEvents.pop();
renderEvent(lastEvent);
// Display nth event:
const index = 5; // for example: display 5th event saved
const storedEvents = JSON.parse(localStorage.getItem("Events"));
if (!storedEvents) throw new Error('No events');
const event = storedEvents[index];
renderEvent(event);

Store object temporarily without using database

I am learning the Object in javascript. In the following code, whenever I click Spawn, a new player is immediately spawned. What I want to do is, when I click Spawn, the player not immediately spawned instead a button with their name on it is created. And then when I click that button, the player whose name in that button is spawned.
I know I can do this easily if I have the database of player but what if this is just temporary, so there is no database. How can I do that?
function spawnPlayer() {
var name_element = document.getElementById('name')
var race_element = document.getElementById('race')
var job_element = document.getElementById('job')
var player = new Player(name_element.value, race_element.value, job_element.value)
var msg = player.race+' '+player.job+' '+player.name+' enter the arena.'
var player_element = document.getElementById('player')
player_element.innerHTML += '<p>'+msg+'</p>'
name_element.value = ''
race_element.value = ''
job_element.value = ''
}
function Player(name, race, job) {
this.name = name
this.race = race
this.job = job
}
<input type="text" placeholder="name" id="name">
<br>
<input type="text" placeholder="race" id="race">
<br>
<input type="text" placeholder="job" id="job">
<br>
<input type="button" onclick="spawnPlayer()" value="Spawn">
<div id="player">
</div>

I need to display a message containing variables (answers from form) after form submit

I need to display the answer from the form in a story. The story must be displayed below the form only after the form is successfully submitted (not an alert), and with the form remaining on the page (not a new page). I am able to insert the form values into the story, but need help with displaying the story after form is submitted. I cannot use anything but html and javascript. I think this can be done with innerHTML.
<head><title>Questions</title>
<script type = "text/javascript" src="quiz1.js">
</script>
</head><body>
<h1>Tell Me About Yourself</h1>
<form name = "the_form" action = "" method = "post"
onSubmit = "var the_result = checkMandatory(); return the_result;">
Full Name:<input type = "text" name = "name" id = "name" /><br/>
Favourite Animal:<input type = "text" name = "animal" id = "animal"><br/>
Favourite Food:<input type = "text" name = "favFood" id = "favFood"><br/>
Favourite Destination:<input type = "text" name = "destination" id = "desitnation"><br/>
Least Favourite Food:<input type = "text" name = "leastFav" id = "leastFav"><br/>
Happiest Moment:<input type = "text" name = "moment" id = "moment"><br/>
Adjective that describes you:<input type = "text" name = "adjective" id = "adjective"><br/>
<br>
<input type="button" value="Submit" onClick = "checkMandatory(); return false;"/><br />
<br />
</form>
<div id="storyDiv"></div>
</body>
</html>
function checkMandatory()
{
// check the text field
// make a var for each question to access easier eg "favMeal"
var name = window.document.the_form.name.value;
//! means 'not'... flips around the if
if (!(name.indexOf(" ") > 0))
{
alert("You must give your full name.");
//return false stops the program
return false;
} else {
//firstName checks all character from 0 to whenever (space) occurs and strips it
var firstName = name.substring(0,name.indexOf(" "));
var name = window.document.the_form.name.value;
var animal = window.document.the_form.animal.value;
var favFood = window.document.the_form.favFood.value;
var destination = window.document.the_form.destination.value;
var leastFav = window.document.the_form.leastFav.value;
var moment = window.document.the_form.moment.value;
var adjective = window.document.the_form.adjective.value;
//alert("first name is " + firstName);
//use alert firstName to test the firstName function
document.write("The young person's name was "+firstName+". "+firstName+" loved to ride
"+animal+
" almost every day. "+firstName+"'s second happiest moment, only next to "+moment+", was in
"+destination+", where "+favFood+
" was served for breakfast, lunch and dinner. It was only when "+firstName+" was told that
"+favFood+
" is actually made from "+animal+", that it instantly became "+firstName+"'s least
favourite food, even worse than "+leastFav+
", and that made "+firstName+" feel very "+adjective+" indeed.")
//document.getElementById('storyDiv').innerHTML = document.getElementById('name').value;
//document.getElementById(‘storyDiv’).innerHTML="The boy's name was "+firstName;
//document.write(‘storyDiv’).innerHTML="The boy's name was " + firstName;
}
}
You can achieve this by posting your form using ajax.
Don't call writethetext(); in your submit button
I'll use jQuery in my solution:
$(function() {
$("form").on("submit", function(e) {
var data = JSON.stringify($("form").serializeArray());
e.preventDefault();
$.post("yourserver/path/", data, function(result) {
writethetext(result);
});
});
});
function checkMandatory() {
// check the text field
// make a var for each question to access easier eg "favMeal"
var name = window.document.the_form.name.value;
//! means 'not'... flips around the if
if (!(name.indexOf(" ") > 0)) {
alert("You must give your full name.");
//return false stops the program
return false;
} else {
//firstName checks all character from 0 to whenever (space) occurs and strips it
var firstName = name.substring(0, name.indexOf(" "));
//alert("first name is " + firstName);
//use alert firstName to test the firstName function
}
}
function writethetext() {
document.getElementById(‘storyDiv’).innerHTML =
("There once was a boy named" + name;)
var firstName = name.substring(0, name.indexOf(" "));
var name = window.document.the_form.name.value;
var animal = window.document.the_form.animal.value;
var favFood = window.document.the_form.favFood.value;
var destination = window.document.the_form.destination.value;
var leastFav = window.document.the_form.leastFav.value;
var moment = window.document.the_form.moment.value;
var adjective = window.document.the_form.adjective.value;
}
function writethetext(text) {
document.getElementById(‘storyDiv’).innerHTML = text;
}
}
<html>
<head>
<title>Questions</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="quiz1.js">
</script>
</head>
<body>
<h1>Tell Me About Yourself</h1>
<form name="the_form" action="" method="post" onSubmit="var the_result = checkMandatory(); return the_result;">
Full Name:
<input type="text" name="name" id="name" />
<br/>Favourite Animal:
<input type="text" name="animal" id="animal">
<br/>Favourite Food:
<input type="text" name="favFood" id="favFood">
<br/>Favourite Destination:
<input type="text" name="destination" id="desitnation">
<br/>Least Favourite Food:
<input type="text" name="leastFav" id="leastFav">
<br/>Happiest Moment:
<input type="text" name="moment" id="moment">
<br/>Adjective that describes you:
<input type="text" name="adjective" id="adjective">
<br/>
<br>
<input type="button" value="Submit" onClick="checkMandatory();
return false;" />
<br />
<br />
</form>
<div id="storyDiv"></div>
</body>
</html>

Categories

Resources