Appending Value to LocalStorage - javascript

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))
}

Related

it seems that i only have one key in my localstorage and it keeps storing all the values into it(localstorage)

hey i am trying to make a phonebook where everytime i add someones name and phonenumber it displays it into the front page and then i can remove or edit...
now i have tried to add a remove function so it removes only the one row or name i choose after many tries i noticed in the application(in the inspect where the developers tools) there is only one key and it seems like i am storing all the arrays (values) into it , now what if i want to remove one value only from the key i am not sure if its possible
maybe i have to make it so i have multiple keys with each key with its own value i am not sure
this is my js code
"use strict";
function showOverlay(showButton, showContainer) { // this whole funciton opens up the overlay
const addButton = document.querySelector("." + showButton);
addButton.addEventListener("click", function addSomthing() {
document.querySelector("." + showContainer).style.display = 'block';
});
} //end of function
showOverlay("addBtn", "formContainer");
function cancelOverlay(cancelButton, showContainer) { //this dynamic funciton helps with closing overlays after we are done with the event
const removeOverlay = document.querySelector("." + cancelButton);
removeOverlay.addEventListener("click", function removeSomthing() {
document.querySelector("." + showContainer).style.display = 'none';
});
} //end of function
cancelOverlay("cancelOverlay", "formContainer");
//
let phoneArray = [];
window.onload = init;
const submitButton = document.getElementById("submitButton");
submitButton.addEventListener("click", function addPerson() {
const person = {
name: document.getElementById("name").value,
phoneNumber: document.getElementById("phone").value
};
if (person.name != "" && person.phoneNumber != "") {
phoneArray = JSON.parse(localStorage.getItem("person")) || [];
phoneArray.push(person);
localStorage.setItem("person", JSON.stringify(phoneArray));
phoneArray = localStorage.getItem("person");
phoneArray = JSON.parse(phoneArray);
window.location.reload(true);
} //end if
} //end addPerson)
);
function createLayout(person) {
const divv = document.getElementById("outPutContainer");
let row = document.createElement("ul");
row.innerHTML = `
<li>${person.name} </li>
<li>${person.phoneNumber} </li>
<button class="insideRemoveBtn"> - </button>
`;
divv.appendChild(row);
} //end of function
function getPersonArray() {
return JSON.parse(localStorage.getItem("person"));
} //end of function
function init() {
const personArray = getPersonArray();
for (let i = 0; i < personArray.length; i++) {
const person = personArray[i];
createLayout(person);
const insideRemoveBtn = document.querySelector(".insideRemoveBtn");
insideRemoveBtn.addEventListener("click", function removeSingleItem() {
localStorage.removeItem('person');
location.reload(true);
});
}
} //end of function
const removeAllBtn = document.getElementById("removeAllBtn");
removeAllBtn.addEventListener("click", function removeAll() {
localStorage.clear();
location.reload(true);
});
and this is my html code if needed
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PhoneBook</title>
<link rel="stylesheet" href="Css/Whole.css">
<script defer src="JavaScript/PU.js"></script>
</head>
<body>
<h1>PhoneBook</h1>
<div class="childContainer">
<div class="buttonsContainer">
<div>
<input type="search" placeholder="search" class="searchBar"></div>
<div class="buttonsRightSide"> <button value="submit" id="addBtn" class="addBtn">+</button>
<button value="submit" id="removeAllBtn" class="removeAllBtn">-</button>
<button value="submit" id="saveBtn" class="saveBtn">*</button></div>
</div>
<div class="formContainer">
<form class="addForm" id="addForm">
<h2>Create Contact</h2>
<label for="name">First name*:</label>
<input id="name" type="text" pattern="[A-Z][a-zA-Z]{3,7}" required><br>
<label for="phoneNumber">Phone number*:</label>
<input id="phone" type="number" pattern="[0][5][0-8][ -]?\d{7}" required><br>
<label for="Adress">Address:</label>
<input type="text" id="Address"><br>
<label for="Email">Email:</label>
<input type="email" id="Email"><br>
<label for="Description">Description:</label>
<textarea type="text" id="Description"></textarea><br>
<div class="sendCancelButtons">
<button type="submit" class="submitButton" id="submitButton">Send</button>
<button value="submit" class="cancelOverlay">Cancel</button></div>
</form>
</div>
<div id="outPutContainer" class="outPutContainer">
</div>
</div>
</body>
</html>
any hints and suggestions are welcome and thanks in advance <3
From what I understood from your question, you are storing all your phonebook data inside person key. For deleting any specific "person" from the localStorage you can parse the array once again and then remove that "person" from array and save it back to localStorage. I'm assuming you want to remove person by it's phone number.
function removeByPhoneNumber(phoneNumber){
const prevArray = JSON.parse(localStorage.getItem("person")) || [];
const newArray = prevArray.filter(_person => _person.phoneNumber !== phoneNumber)
localStorage.setItem("person", JSON.stringify(newArray))
}

Double Square Brackets in my Javascrip Arrays within localStorage?

I have managed to get data registering to my localStorage as arrays, however I have three queries:
Why are there double square brackets around my array?
How do I change the name field to the respective html ID?
Data returning as undefined when I try to retrieve it from the localStorage?
The output I am looking for in my localStorage is:
bookings: [
[0]{fname: "John", lname: "Smith" }
[1]{fname: "Jane", lname: "Doe" }
]
But I am currently getting:
bookings: [
[0][{name: "fname" value: "John"},{name: "lname": value: "Smith" }]
[1][{name: "fname" value: "Jane"},{name: "lname": value: "Doe" }]
]
I understand how to change the name value when items are hardcoded but I am initialising an empty array in my JS and not sure where the error is, I have tried assigning a value to the array [0] but then it doesn't register anything. I have also tried the data.flat() method which does nothing.
The issue is my next step is to amend and delete items so I need to try and understand the structure. Currently I am getting undefined when I try to get data from storage, I have provided my remove function (currently to show) below, I know it is wrong but I think the issue is to do with how I am storing the data. Sorry I have asked so many questions on this but I am new to JS and still learning. I am struggling with searches as there are so many variations of Javascript and getting a lot of answers relating to C# or Python which isn't helping.
Here is my code:
//var bookings = [];
var bookings = localStorage.getItem("bookings");
$("#submit").click(function () {
//bookings = JSON.parse(localStorage.getItem("bookings")) || [];
bookings = (bookings) ? JSON.parse(bookings) : [];
var newBooking = $("#regForm").serializeArray();
bookings.push(newBooking)
var json = JSON.stringify(bookings);
const newData = bookings.flat();
window.localStorage.setItem("bookings", json);
});
$("#remove").click(function () {
var strBookings;
var i;
strBookings = localStorage.getItem("bookings");
//document.write("<p>" + strBookings + "</p>");
bookings = JSON.parse(strBookings);
for (i = 0; i < strBookings.length; i++) {
document.write("<p>" + strBookings[i].value + "</p>");
}
//localStorage.removeItem('bookings');
});
Form
<form id="regForm" name="regForm" class="col-sm-6">
<div class="row">
<input type="text" id="fname" placeholder="First Name" name="fname" required>
<input type="text" id="lname" placeholder="Last Name" name="lname" required>
<input id="submit" type="submit" value="Submit">
</div>
</form>
Show
//var bookings = [];
var bookings = localStorage.getItem("bookings");
$("#submit").click(function () {
//bookings = JSON.parse(localStorage.getItem("bookings")) || [];
bookings = (bookings) ? JSON.parse(bookings) : [];
var newBooking = $("#regForm").serializeArray();
bookings.push(newBooking)
var json = JSON.stringify(bookings);
const newData = bookings.flat();
window.localStorage.setItem("bookings", json);
});
$("#remove").click(function () {
var strBookings;
var i;
strBookings = localStorage.getItem("bookings");
//document.write("<p>" + strBookings + "</p>");
bookings = JSON.parse(strBookings);
for (i = 0; i < strBookings.length; i++) {
document.write("<p>" + strBookings[i].value + "</p>");
}
//localStorage.removeItem('bookings');
});
<form id="regForm" name="regForm" class="col-sm-6">
<div class="row">
<input type="text" id="fname" placeholder="First Name" name="fname" required>
<input type="text" id="lname" placeholder="Last Name" name="lname" required>
<input id="submit" type="submit" value="Submit">
</div>
</form>
<button id="remove" value="Remove">Show</button>

Just trying out to check whether the value is present in array or not

I am trying to write a function in jQuery.
var arr1 = ["Jcob", "Pete", "Fin", "John"];
var str = $("#fname").val();
if (jQuery.inArray(str, arr1))
$("#lname").text("Bob");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="fname" name="fname">
<input type="text" id="lname" name="lname">
Please check my fiddle here
What it will do it the user will give the value in the first input box the jQuery function will check if the value is present in that array it will fill the second input box with the given text.
Three things:
You need to add an event listener to the first input to constantly keep checking when someone inputs something.
Before selecting elements in the DOM, make sure the DOM is ready.
You don't need jQuery at all here. Like most things, very easy to do without jQuery.
const names = [ "Jcob", "Pete", "Fin", "John" ];
document.addEventListener('DOMContentLoaded', function() {
const fname = document.getElementById('fname');
const lname = document.getElementById('lname');
fname.addEventListener('input', function(event) {
lname.value = names.includes(fname.value) ? 'Bob' : '';
});
});
<input type="text" id="fname" name="fname">
<input type="text" id="lname" name="lname">
If you insist on jQuery (which I do strongly recommend you shouldn't until you are proficient with the native DOM API):
const names = [ "Jcob", "Pete", "Fin", "John" ];
$(document).ready(function() {
const $fname = $('#fname');
const $lname = $('#lname');
$fname.on('input', function(event) {
if ($.inArray($fname.val(), names) > -1) {
$lname.val('Bob');
} else {
$lname.val('');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="fname" name="fname">
<input type="text" id="lname" name="lname">
Try this:
<body>
<input type="text" id="fname" name="fname">
<input type="text" id="lname" name="lname">
<button onclick="checkValue()">Click</button>
<script>
var arr1 = ["Jcob", "Pete", "Fin", "John"];
function checkValue() {
var str = $("#fname").val();
var val = jQuery.inArray(str, arr1);
if (val === -1) {
console.log("no value");
}
else {
$("#lname").val("Bob");
}
}
</script>
</body>

Get data for form input array using specific key

So, let's say I have an HTML form like this:
<form id="myForm">
<input type="text" name="dummy">
<input type="text" name="people[0][first_name]" value="John">
<input type="text" name="people[0][last_name]" value="Doe">
<input type="text" name="people[1][first_name]" value="Jane">
<input type="text" name="people[1][last_name]" value="Smith">
</form>
And I want to get a JavaScript array that matches the values of real. For example:
// If there was a sweet function for this...
var people = getFormDataByInputName( 'people' );
// Value of `people` is...
// [
// {
// 'first_name' : 'John',
// 'last_name' : 'Doe'
// },
// {
// 'first_name' : 'Jane',
// 'last_name' : 'Smith'
// }
// ]
Is there any easy way of doing that for just a specific form item (in this case, people)? Or would I have to serialize the entire form an then just extract the element I want?
I also thought of potentially using the following approach:
var formData = new FormData( document.querySelector( '#myForm' ) );
var people = formData.get( 'people' );
But that doesn't appear to work; people is just null after that.
You could do this with plain js using reduce method and return each person is one object.
const form = document.querySelectorAll('#myForm input');
const data = [...form].reduce(function(r, e) {
const [i, prop] = e.name.split(/\[(.*?)\]/g).slice(1).filter(Boolean)
if (!r[i]) r[i] = {}
r[i][prop] = e.value
return r;
}, [])
console.log(data)
<form id="myForm">
<input type="text" name="dummy">
<input type="text" name="people[0][first_name]" value="John">
<input type="text" name="people[0][last_name]" value="Doe">
<input type="text" name="people[1][first_name]" value="Jane">
<input type="text" name="people[1][last_name]" value="Smith">
</form>
function getObject(name, key) {
if(key.includes(name)) {
var splitStr = key.split(/\[|\]/g);
return {
index: splitStr[1],
key: splitStr[3],
}
}
return null;
}
function getFormDataByInputName(name) {
var formData = new FormData( document.querySelector('#myForm'));
var results = [];
for (var key of formData.keys()) {
var obj = getObject(name, key);
if (obj) {
if (results[obj.index]) results[obj.index][obj.key] = formData.get(key);
else results[obj.index] = { [obj.key]: formData.get(key) };
}
}
return results;
}
var people = getFormDataByInputName('people');
console.log(people);
<form id="myForm">
<input type="text" name="dummy">
<input type="text" name="people[0][first_name]" value="John">
<input type="text" name="people[0][last_name]" value="Doe">
<input type="text" name="people[1][first_name]" value="Jane">
<input type="text" name="people[1][last_name]" value="Smith">
</form>
Your code won't work because to HTML/JS name is just a string that it sends to the server when the form is submitted (the name in the name/value pairs). You might think it is arrays, but HTML/JS doesn't.
So no one-liner to get the job done. Try this: In your HTML, add <div class="name"> ...
(UPDATE: thanks for the idea, #Nenad, I've never tried one of these snippets)
var people = [];
$('.name').each(function() {
people.push({
first_name: $('input:nth-child(1)', this).val(),
last_name: $('input:nth-child(2)', this).val()
});
});
console.log(people);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<input type="text" name="dummy">
<div class="name">
<input type="text" value="John">
<input type="text" value="Doe">
</div>
<div class="name">
<input type="text" value="Jane">
<input type="text" value="Smith">
</div>
</form>
Use CSS attribute prefix selector, such as
form.querySelectorAll('[name^="people[]"]')
You can use a for-loop to get all peoples, as such
const MAX_PEOPLES = 2;
const list = [];
for (i = 0; i <= MAX_PEOPLES; i++) {
const eles = form.querySelectorAll(`[name^="people[${i}]`);
if (eles.length !== 2)
break;
list.push({
first_name: eles[0].value,
last_name: eles[1].value
});
}
that yields
[
{
"first_name":"John",
"last_name":"Doe"
},
{
"first_name":"Jane",
"last_name":"Smith"
}
]

i want to search a string from the json object in javascript

I want to search the House Name from all the input the user provided.
so if the user details are as:
[{"houseName":"man","houseType":"villa","houseFloors":"seven","houselocation":"Seattle"},{"houseName":"band","houseType":"small","houseFloors":"two","houselocation":"washington DC"}]
If i provide search as man ,it should give me as:
[{"houseName":"man","houseType":"villa","houseFloors":"seven","houselocation":"Seattle"}]
The code is as :
<html>
<head>
<title>JavaScript</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label>House Name
<input type='text' name='houseName' id='houseName' placeholder="House Name">
</label>
<br>
<br>
<label>House type
<input type='text' name='houseType' id='houseType' placeholder="House type">
</label>
<br>
<br>
<label>House Floors:
<input type='text' name='houseFloors' id='houseFloors' placeholder="House Floors">
</label>
<br>
<br>
<label>House Location:
<input type='text' name='houselocation' id='houselocation' placeholder="House Location">
</label>
<br>
<br>
<div>
<label>search:
<input type="text" name="search" id="search-input" placeholder="search">
<input type="submit">
</div>
<button type="button" id="add">Add Details</button>
<button type="button" id="print">Show</button>
<pre></pre>
<script>
var list = [],
$ins = $('#houseName, #houseType, #houseFloors, #houselocation'),
var counter = {
houseName: {},
houseType: {},
houseFloors: {},
houselocation: {}
};
$('#add').click(function() {
var obj = {},
valid = true;
$ins.each(function() {
var val = this.value;
if (val) {
obj[this.id] = val;
} else {
alert(" Cannot be blank");
return false;
}
});
if (valid) {
list.push(obj);
$ins.val('');
}
});
$('#print').click(function() {
$('pre').text(JSON.stringify(list) + '\n\n');
})
var keyword = $('#search-input').val();
var filteredList = list.filter(function(user){
return user.houseName === 'man'; // Or u can use indexOf if u want check if the keyword is contained
});
</script>
</body>
</html>
You may use Array.prototype.filter.
In ur case it will look like
var filteredList = list.filter(function(user){
return user.houseName === 'man'; // Or u can use indexOf if u want check if the keyword is contained
});
If u would like to search it with an input box, there will be a little bit more work to do:
//The follow code should be executed when u are going to do the 'search' action
//It could be an click on a button, or just in a listener which is triggered when the search box fires 'change' events
//First u need to get the keyword from the search input box:
var keyword = $('#search-input').val();
//maybe do some value check
//if (keyword === '') return;
//then get the filtered List
var filteredList = list.filter(function(user){
return user.houseName === keyword;
});
//Finally update the UI based on the filtered List
//Maybe jQuery's DOM functions could be helpful

Categories

Resources