Not Able To Display Multiple Things in an Array - javascript

I have made an array that stores what I have inputted into local storage which works 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>
And Currently, I am able to display them like this however it only displays 1 at a time and if I add this code in again but trying to display something else in the array it won't display either.
<h2>All Upcoming Events</h2>
<h2 id='input1'> </h2>
<h2 id='input2'> </h2>
<h2 id='input3'> </h2>
<h2 id='input4'> </h2>
<!-- running script here will populate H2's with values from local storage -->
<script>
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;
};
const index = 0; // 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);
</script>

Use a <ul> element, and add items to it in a loop.
<h2>All upcoming events</h2>
<ul id="events"></ul>
const storedEvents = JSON.parse(localStorage.getItem("Events"));
var html = '';
storedEvents.forEach({name, dateTime, location, notes}) => {
html += `<li><h3>${name}</h3><h3>${dateTime}</h3><h3>${location}</h3><h3>${notes}</h3></li>';
});
document.getElementById("events").innerHTML = html;

Related

How do I display multiple inputs?

const form = document.querySelector("#user-form");
const userInput = document.querySelector("#name", "#surname", "#age", "#country");
const userList = document.querySelector(".list-group");
const firstCardBody = document.querySelectorAll(".card-body")[0];
const secondCardBody = document.querySelectorAll(".card-body")[1];
const filter = document.querySelector("#filter");
const clearButton = document.querySelector("#clear-users");
<form id="user-form" name="form">
<div class="form-row">
<div class="form-group col-md-6">
<input class="form-control" type="text" name="name" id="name" placeholder="İsim">
</div>
<div class="form-group col-md-6">
<input class="form-control" type="text" name="surname" id="surname" placeholder="Soyadı">
</div>
<div class="form-group col-md-6">
<input class="form-control" type="text" name="age" id="age" placeholder="Yaş">
</div>
<div class="form-group col-md-6">
<input class="form-control" type="text" name="country" id="country" placeholder="Ülke">
</div>
</div>
<button type="submit" class="btn btn-primary">Bilgilerinizi Kaydedin</button>
</form>
My form looks like this.
But when I run my JS code, it only shows me the name not surname, age or country. How do I display all of them?
enter image description here
document.querySelector cannot be use the way you use it as it returns the first matched element (in your case the name input). To get all input fields you can do it like this:
const userInput = document.querySelectorAll(".form-control");
This returns all 4 input fields in an array which can be iterated via
userInput.forEach(input => { ... });
Get a specific element like this:
Array.from(userInput).find(input => input.id === "name");
Another approach would be to get the input fields via their ID's:
const name = document.querySelector("#name");
const surname= document.querySelector("#surname");
const age = document.querySelector("#age");
const country = document.querySelector("#country");

how do I store a value from a date and time form

I have a reminder app I am working on and I'm not able to store the date and time, only the name and a description. For now I just need to get it into local storage and then deal with retrieving the later.
let reminders = [];
const addReminders = (ev) => {
ev.preventDefault();
let reminder = {
ReminderInput: document.getElementById('ReminderInput').value,
InfoInput: document.getElementById('InfoInput').value
}
localStorage.setItem('ReminderInput', JSON.stringify(ReminderInput));
localStorage.setItem('InfoInput', JSON.stringify(InfoInput));
localStorage.setItem('DateInput' JSON.stringify(DateInput));
}
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('btn').addEventListener('click', addReminders);
});
<form id="todoForm">
<label for="ReminderInput">Reminder</label>
<input class="u-full-width" type="text" id="ReminderInput">
<label for="DateInput">Date</label>
<input class="u-full-width" type="datetime-local" id="DateInput">
<label for="InfoInput">Additional Information</label>
<textarea class="u-full-width" type="text" placeholder="Remember to..." id="InfoInput"></textarea>
<button type="button" id="btn" class="button-primary">Add Reminder</button>
</form>
Hers' the code that needs to be corrected, screenshot to show it works:
let reminder = {
ReminderInput: document.getElementById('ReminderInput').value,
InfoInput: document.getElementById('InfoInput').value,
DateInput: document.getElementById('DateInput').value
}
localStorage.setItem('ReminderInput', JSON.stringify(reminder.ReminderInput));
localStorage.setItem('InfoInput', JSON.stringify(reminder.InfoInput));
localStorage.setItem('DateInput',JSON.stringify(reminder.DateInput));
}

Not saving to local storage

I'm stuck on what I have done while playing around with the code. I had it saving to local storage but now its not. Could someone help me troubleshoot this
<form name="todoForm" action="" method="get">
Reminder : <input type="text" name="ReminderInput" id="ReminderInput"><br />
Date: <input type="datetime-local" name="DateInput" id="DateInput"><br />
Extra Information : <input type="text" name="InfoInput" id="InfoInput"><br />
<button onclick="storeValues(reminder)" type=submit>Submit</button>
</form>
<script>
function storeValues(e) {
e.preventDefault();
let storedReminders = JSON.parse(localStorage.getItem("Reminders")) || [];
const newReminderDetails = {
ReminderInput: document.getElementById('ReminderInput').value,
DateInput: document.getElementById('DateInput').value,
InfoInput: document.getElementById('InfoInput').value
}
storedReminders.push(newReminderDetails);
localStorage.setItem("Reminders", JSON.stringify(storedReminders));
console.log('storedReminders', storedReminders);
}
</script>
write event rather then reminder
<button onclick="storeValues(event)" type="submit">Submit</button>
you didn't do anything wrong but there is a tiny mistake which is we don't do click event on forms instead we using a submit event. so here is my solution
HTML Code:
<form id="todoForm" action="" method="get">
Reminder : <input type="text" name="ReminderInput" id="ReminderInput"><br />
Date: <input type="datetime-local" name="DateInput" id="DateInput"><br />
Extra Information : <input type="text" name="InfoInput" id="InfoInput"><br />
<button type=submit>Submit</button>
</form>
JS Code
function storeValues(e) {
e.preventDefault();
let storedReminders = JSON.parse(localStorage.getItem("Reminders")) || [];
const newReminderDetails = {
ReminderInput: document.getElementById('ReminderInput').value,
InfoInput: document.getElementById('InfoInput').value
}
storedReminders.push(newReminderDetails);
localStorage.setItem("Reminders", JSON.stringify(storedReminders));
console.log('storedReminders', storedReminders);
}
document.getElementById("todoForm").addEventListener("submit",storeValues );

Sumbit user name and surname and go to the next page

I can't figure out how to connect function that will save name and surname in local storage and go to the other page. If you could point out the problem I would be very grateful :)
index.html
<form id="from" action="" method="post">
<div>
<pre> <label for="name">Име</label></pre>
<input id="name" name="name" type="text" required>
<br>
<pre><label for="surname"> Презиме </label></pre>
<input id="surname" surname="surname" type="text" required>
<br><br>
</div>
<button onclick="sumbit()"> Започни тест </button>
</form>
script.js
let infs = [];
const addInf= (ev)=>{
ev.preventDefault(); //to stop the form submitting
let inf = {
id: Date.now(),
name: document.getElementById('name').value,
surname: document.getElementById('surname').value
}
infs.push(inf);
document.forms[0].reset(); // to clear the form for the next entries
//saving to LS
localStorage.setItem('MyInfList', JSON.stringify(infs) );
}
document.addEventListener('DOMContentLoaded', ()=>{
document.getElementById('btn').addEventListener('click', addInf);
});
Try this, use window.location for redirecting to another page, it has same functionality as href.
<form id="from" action="" method="post">
<div>
<pre> <label for="name">Име</label></pre>
<input id="name" name="name" type="text" required>
<br>
<pre><label for="surname"> Презиме </label></pre>
<input id="surname" surname="surname" type="text" required>
<br><br>
</div>
<a><button id="btn"> Започни тест </button> </a>
</form>
<script>
let infs = [];
const addInf = (ev) => {
ev.preventDefault(); //to stop the form submitting
let inf = {
id: Date.now(),
name: document.getElementById('name').value,
surname: document.getElementById('surname').value
}
infs.push(inf);
//saving to LS
localStorage.setItem('MyInfList', JSON.stringify(infs));
document.forms[0].reset(); // to clear the form for the next entries
window.location = "quiz.html"
}
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('btn').addEventListener('click', addInf);
});
</script>

How do I group inputs in Local storage to be one "Event" categorized by my Date time input

In my app I collect information from the user and store it in Local storage using javascript like this.
Event Name (1 to 20 characters):
<input type="text" id="eventname" name="eventname" required
minlength="1" maxlength="20" size="20">
<label for="datetime">Event Date and Time:</label>
<input type="datetime-local" id="date" name="date" required
minlength="1" maxlength="20" size="20">
<label for="eventlocation">Event Location (1 to 20 characters):</label>
<input type="text" id="location" name="location" required
minlength="1" maxlength="20" size="20">
<label for="notes">Notes (0 to 50 characters): </label>
<input type="text" id="notes" name="notes" required
minlength="0" maxlength="50" size="50">
<script src="app.js"></script>
I then have an app.js document which puts it into local storage
const locationTxt = document.querySelector('#location');
locationTxt.addEventListener('change', (event) => {
localStorage.setItem('location', event.target.value);
function getSavedData() {
console.log('location', localStorage.getItem('location'));
(except i have these fucntions for each of the inputs.)
How Would i go about taking all these inputs in locale storage and displaying it as 1 event that is able to be categorized by time?
One way would be to store event data in an object:
{
'01-02-1900': [
... // Array of events
],
'01-01-1900': [
... // Array of events
],
...
}
And then using JSON.parse and JSON.stringify to read/write to localStorage. 😊
For instance:
/**
* This override localStorage in Stack Snippet
*/
const customStorage = { data: {} };
customStorage.getItem = index => customStorage.data[index] || null;
customStorage.setItem = (index, payload) =>
(customStorage.data[index] = payload);
/**
* Replace customStorage with localStorage below.
*/
const inputs = document.querySelectorAll("input");
const storageIndex = "myTestStorage";
const storeInLocal = formData => {
const { date, event } = formData;
const toStore = JSON.parse(customStorage.getItem(storageIndex)) || {};
if (!toStore[date]) toStore[date] = [];
toStore[date].push(event);
customStorage.setItem(storageIndex, JSON.stringify(toStore));
};
const readForm = () => {
let values = {};
inputs.forEach(({ name, value }) => {
values[name] = value;
});
const { date, eventname, location, notes } = values;
return {
date,
event: {
eventname,
location,
notes
}
};
};
const outputStorage = () => {
const storage = customStorage.getItem(storageIndex) || "";
document.getElementById("output").innerText = storage;
};
document.getElementById("eventForm").addEventListener("submit", e => {
e.preventDefault();
const formData = readForm();
storeInLocal(formData);
outputStorage();
});
<!DOCTYPE html>
<html lang="en">
<head>
<title>Store form data in localStorage</title>
<link
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
rel="stylesheet"
/>
<style>
pre {
white-space: pre-wrap;
}
</style>
</head>
<body>
<main id="app" role="main" class="container">
<form id="eventForm">
<div class="form-group row">
<label for="eventname">Event Name</label>
<div class="col-sm-6">
<input
type="text"
id="eventname"
name="eventname"
required
minlength="1"
maxlength="20"
/>
</div>
</div>
<div class="form-group row">
<label for="datetime">Event Date and Time:</label>
<div class="col-sm-6">
<input
type="datetime-local"
id="date"
name="date"
required
minlength="1"
maxlength="20"
/>
</div>
</div>
<div class="form-group row">
<label for="eventlocation">Event Location</label>
<div class="col-sm-6">
<input
type="text"
id="location"
name="location"
required
minlength="1"
maxlength="20"
/>
</div>
</div>
<div class="form-group row">
<label for="notes">Notes</label>
<div class="col-sm-6">
<input
type="text"
id="notes"
name="notes"
required
minlength="0"
maxlength="50"
/>
</div>
</div>
<button type="submit" class="btn btn-primary">Save</button>
</form>
<h1 class="h4">Output</h1>
<p>Hit "save" multiple times, and change the date occasionally.
<p>
<pre id="output"></pre>
</p>
</main>
</body>
</html>

Categories