-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
64 lines (60 loc) · 1.75 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
const notesForm = document.querySelector("#notesForm");
const displayNoteContainer = document.querySelector("#displayNotes");
showNotes();
// Form Handling
notesForm.addEventListener("submit", (e) => {
e.preventDefault();
const formData = new FormData(notesForm);
const note = formData.get("note");
const title = formData.get("title");
addNote(title, note);
});
// Show Notes
function showNotes() {
const notes = JSON.parse(localStorage.getItem("notes"));
displayNoteContainer.innerHTML = "";
notes?.forEach((note, index) => {
displayNoteContainer.innerHTML += `<div class="card" style="width: 16rem;">
<div class="card-body text-center">
<h5>${note.title}</h5>
<p class="card-text">
${note.data}
</p>
<button data-noteindex='${index}' onclick="removeNote(this.dataset.noteindex)" class="btn btn-primary">
Delete Note
</button>
</div>
</div>`;
});
}
// Add Notes
function addNote(title, data) {
if (title === "" || data === "") return null;
const noteObj = {
title,
data,
};
const notes = JSON.parse(localStorage.getItem("notes"));
if (notes !== null) {
localStorage.setItem("notes", JSON.stringify([...notes, noteObj]));
alert("Note added successfully!");
showNotes();
return;
}
localStorage.setItem("notes", JSON.stringify([noteObj]));
alert("Note added successfully!");
showNotes();
}
// Remove Note
function removeNote(noteIndex) {
if (noteIndex === "") return null;
const notes = JSON.parse(localStorage.getItem("notes"));
const confirmation = confirm(
`Are your sure you want to delete the note ${notes.at(noteIndex).data}`
);
if (confirmation) {
notes.splice(noteIndex, 1);
localStorage.setItem("notes", JSON.stringify(notes));
showNotes();
}
}