javascript Array Error inside object,cant access push of undefine - javascript

Here error is coming is can't access a property of undefined, In this.dataLog when I'm trying to push something in it. Please resolve the same. It is showing this.dataLog array as undefined.Here error is coming is can't access a property of undefined, In this.dataLog when I'm trying to push something in it. Please resolve the same. It is showing this.dataLog array as undefined.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://kit.fontawesome.com/9147344c85.js" crossorigin="anonymous" defer></script>
<!-- <link href="https://unpkg.com/tailwindcss#^1.0/dist/tailwind.min.css" rel="stylesheet"> -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<link rel="stylesheet" href="index.css">
<script src="index.js" type="text/javascript" defer></script>
<title>Document</title>
</head>
<body>
<div class="alert alert-success height" role="alert">
<img src="https://source.unsplash.com/random/70x100" id="main-img" class="">
<span>NatureFresh.com</span>
</div>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a id="login-link" class="navbar-brand" href="#">Login</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown"
aria-haspopup="true" aria-expanded="false">
Dropdown
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another action</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="#">Something else here</a>
</div>
</li>
<li class="nav-item">
<a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a>
</li>
</ul>
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
</form>
</div>
</nav>
<div class="dropdown">
<a class="btn btn-secondary dropdown-toggle side-anchor" href="#" role="button" id="dropdownMenuLink"
data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Important links
</a>
<div id="login-back">
<form id="login">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" aria-describedby="basic-addon1" placeholder="Username">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Email">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control"placeholder="Password" id="exampleInputPassword1">
</div>
<div class="form-group form-check">
<input type="checkbox" class="form-check-input" id="exampleCheck1">
<label class="form-check-label" for="exampleCheck1">Check me out</label>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
<div class="alert alert-success sucessful" role="alert">
<h4 class="alert-heading">Welcome Back!</h4>
<hr>
<p></p>
</div>
<div class="dropdown-menu inside-anchor" aria-labelledby="dropdownMenuLink">
<a class="dropdown-item" href="https://www.facebook.com/">Facebook</a>
<a class="dropdown-item" href="#">Twitter</a>
<a class="dropdown-item" href="#">Gmail</a>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js"
integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"
integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI"
crossorigin="anonymous"></script>
</body>
</html>
class LoginDisplay {
constructor() {
this.dataLog=[];
}
render() {
// let loginLink = document.querySelector("#login-link");
let loginBack = document.querySelector("#login-back");
let loginForm = document.querySelector("#login");
let inputName = document.querySelector("#name");
let inputEmail = document.querySelector("input[type=\"email\"]");
let inputPassword = document.querySelector("input[type=\"password\"]");
loginBack.classList.toggle("visible");
loginForm.classList.toggle("visible");
inputName.value = "";
inputEmail = "";
inputPassword = "";
}
validation() {
let loginForm = document.querySelector("#login");
let loginBack = document.querySelector("#login-back");
let sucessAlert = document.querySelector("div[class=\"alert alert-success sucessful\"]");
let inputName = document.querySelector("#name");
let inputEmail = document.querySelector("input[type=\"email\"]");
let inputPassword = document.querySelector("input[type=\"password\"]");
let patt = /^[A-Za-z0-9]{2,}#[a-zA-Z0-9]{1,10}.com$/;
let para = sucessAlert.querySelector("p");
if (patt.test(inputEmail.value) && inputPassword.value === "dhawan") {
loginBack.classList.toggle("visible");
loginForm.classList.toggle("visible");
para.innerHTML = `<h4>Namste! ${inputName.value} <i class="fas fa-check"></i></h4>`;
inputName.value = "";
inputEmail = "";
inputPassword = "";
sucessAlert.classList.toggle("visible");
debugger;
this.dataLog.push(para);
}
// else{
// para.innerHTML=`<h4>`
// }
}
ve(){
console.log(this.dataLog.push("Sudhir"));
}
}
let login = new LoginDisplay();
let loginLink = document.querySelector("#login-link");
let btn= document.querySelectorAll("button[type=\"submit\"]")[1];
loginLink.addEventListener("click", login.render);
btn.addEventListener("click",login.validation)

This is the solution to your problem, but I think it has many ways to do it.
class LoginDisplay {
constructor() {
this.dataLog = [];
}
render() {
// let loginLink = document.querySelector("#login-link");
let loginBack = document.querySelector("#login-back");
let loginForm = document.querySelector("#login");
let inputName = document.querySelector("#name");
let inputEmail = document.querySelector('input[type="email"]');
let inputPassword = document.querySelector('input[type="password"]');
loginBack.classList.toggle("visible");
loginForm.classList.toggle("visible");
inputName.value = "";
inputEmail = "";
inputPassword = "";
}
validation() {
let loginForm = document.querySelector("#login");
let loginBack = document.querySelector("#login-back");
let sucessAlert = document.querySelector(
'div[class="alert alert-success sucessful"]'
);
let inputName = document.querySelector("#name");
let inputEmail = document.querySelector('input[type="email"]');
let inputPassword = document.querySelector('input[type="password"]');
let patt = /^[A-Za-z0-9]{2,}#[a-zA-Z0-9]{1,10}.com$/;
let para = sucessAlert.querySelector("p");
let a = patt.test(inputEmail.value) && inputPassword.value === "dhawan";
console.log(!a);
if (!a) {
loginBack.classList.toggle("visible");
loginForm.classList.toggle("visible");
para.innerHTML = `<h4>Namste! ${inputName.value} <i class="fas fa-check"></i></h4>`;
inputName.value = "";
inputEmail = "";
inputPassword = "";
sucessAlert.classList.toggle("visible");
//debugger;
return para;
}
// else{
// para.innerHTML=`<h4>`
// }
}
ve() {
console.log(this.dataLog.push("Sudhir"));
}
}
let login = new LoginDisplay();
let loginLink = document.querySelector("#login-link");
let btn = document.querySelectorAll('button[type="submit"]')[1];
loginLink.addEventListener("click", login.render);
btn.addEventListener("click", () => {
if (login.validation) {
let result = login.validation();
login.dataLog.push(result);
console.log(login.dataLog); // Here you have your element tag HTML in your Array!
}
});

Related

Why does my delete button does not delete the card

I want to delete the card when we click on the delete button after adding a TODO note
I have created a website which uses localstorage to store notes and display when clicking the create TODO button and it all works but when I click the delete button after the note is created (You have to create a TODO first) it does not delete the div itself
I want to delete the card when we click on the delete button
CODE:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TODO List</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.2/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
<style>
.main-title {
text-align: center;
}
.input {
border: 2px solid grey;
}
.all-todo {
display: flex;
margin: 30px;
}
</style>
</head>
<body>
<nav class="navbar navbar-expand-lg bg-light">
<div class="container-fluid">
<a class="navbar-brand" href="#">TODO List</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse"
data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false"
aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
</ul>
<form class="d-flex" role="search">
<input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success" type="submit">Search</button>
</form>
</div>
</div>
</nav>
<h1 class="main-title">TODO List</h1>
<div class="container">
<div class="mb-3">
<label for="exampleFormControlInput1" class="form-label">Task Name</label>
<input type="text" class="form-control input" id="exampleFormControlInput1">
</div>
<div class="mb-3">
<label for="exampleFormControlTextarea1" class="form-label">Task Details</label>
<textarea class="form-control input" id="exampleFormControlTextarea1" rows="3"></textarea>
</div>
<button type="submit" class="btn btn-primary" id="main-btn">Create TODO</button>
<button type="button" class="btn btn-warning" id="clr">Clear LocalStorage</button>
</div>
<div class="all-todo"></div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.2/dist/js/bootstrap.bundle.min.js"
integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3"
crossorigin="anonymous"></script>
</body>
<script>
let button = document.getElementById("main-btn")
button.onclick = () => {
let key = document.getElementById("exampleFormControlInput1").value
let value = document.getElementById("exampleFormControlTextarea1").value
if (key != "" && value != "") {
iHTML = ""
localStorage.setItem(key, value)
iHTML += `
<div class="card" style="width: 18rem;">
<div class="card-body">
<h5 class="card-title">${key}</h5>
<p class="card-text">${localStorage.getItem(key)}</p>
<button type="button" id="note" onclick='${key}.innerHTML=""' class="btn btn-danger '${key}'">Delete</button>
</div>
</div>
`
document.getElementsByClassName("all-todo")[0].innerHTML += iHTML
}
else {
alert("Task Name or Details cannot be empty!")
}
}
let clr_btn = document.getElementById("clr")
clr_btn.onclick = () => {
localStorage.clear()
}
</script>
</html>
The error is thrown on this line onclick='${key}.innerHTML=""'. You will want to first remove the item from local storage e.g: localStorage.removeItem('${key}') and then remove the html. Theres many way of achieveing this but this.parentElement.parentElement.remove() should be sufficient
The complete button should look something like <button type="button" id="note" onclick="localStorage.removeItem('${key}'); this.parentElement.parentElement.remove()" class="btn btn-danger '${key}'">Delete</button>
Heres a working example:
https://jsfiddle.net/qt83bshd/
Well, i post you a simple solution for your problem.
Instead of use innerhtml to introuce your todos, yo can create the elements.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TODO List</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.2/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
<style>
.main-title {
text-align: center;
}
.input {
border: 2px solid grey;
}
.all-todo {
display: flex;
margin: 30px;
}
/* add css in this poiint to optimize code*/
.card {
width: 18rem;
}
</style>
</head>
<body>
<nav class="navbar navbar-expand-lg bg-light">
<div class="container-fluid">
<a class="navbar-brand" href="#">TODO List</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse"
data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false"
aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="#">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
</ul>
<form class="d-flex" role="search">
<input class="form-control me-2" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success" type="submit">Search</button>
</form>
</div>
</div>
</nav>
<h1 class="main-title">TODO List</h1>
<div class="container">
<div class="mb-3">
<label for="exampleFormControlInput1" class="form-label">Task Name</label>
<input type="text" class="form-control input" id="exampleFormControlInput1">
</div>
<div class="mb-3">
<label for="exampleFormControlTextarea1" class="form-label">Task Details</label>
<textarea class="form-control input" id="exampleFormControlTextarea1" rows="3"></textarea>
</div>
<button type="submit" class="btn btn-primary" id="main-btn">Create TODO</button>
<button type="button" class="btn btn-warning" id="clr">Clear LocalStorage</button>
</div>
<div class="all-todo"></div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.2/dist/js/bootstrap.bundle.min.js"
integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3"
crossorigin="anonymous"></script>
</body>
<script>
let button = document.getElementById("main-btn")
button.onclick = () => {
// collect the div that contains all the todos
let alltodo = document.querySelector(".all-todo");
let key = document.getElementById("exampleFormControlInput1").value
let value = document.getElementById("exampleFormControlTextarea1").value
// and if it any todo create the card
if (key != "" && value != "") {
localStorage.setItem(key, value)
// with create element we can create the card more easy
var todo = document.createElement("div");
todo.setAttribute("class", "card");
var button = document.createElement("button");
button.textContent = "eliminar";
var titulo = document.createElement("h5");
titulo.textContent = key;
button.onclick = () => {
console.log(button.parentElement.remove())
// in this point we can also remove the todo from the local storage wih localstorage.removeItem()
}
// introduce all items in dom
todo.appendChild(titulo)
todo.appendChild(button);
alltodo.appendChild(todo);
// iHTML = ""
// localStorage.setItem(key, value)
// iHTML += `
// <div class="card" style="width: 18rem;">
// <div class="card-body">
// <h5 class="card-title">${key}</h5>
// <p class="card-text">${localStorage.getItem(key)}</p>
// <button type="button" id="note" onclick='${key}.innerHTML=""' class="btn btn-danger '${key}'">Delete</button>
// </div>
// </div>
// `
// document.getElementsByClassName("all-todo")[0].innerHTML += iHTML
}
else {
alert("Task Name or Details cannot be empty!")
}
}
let clr_btn = document.getElementById("clr")
clr_btn.onclick = () => {
localStorage.clear()
}
</script>
</html>

Javascript dropdown menu delete event bug

first of all, I am just a beginner on javascript. and I am trying to coding a todo-list application, I ran into a problem with the deleting future that located in every task. When I try to delete specific task on the application, the application has to compare the id information and delete the task in the relevant id,but aplication not work well, no matter which task I click, it deletes it sequentially from beginning to end.
I also tried with the for-in loop as a solution, but I still got the same result. Where am I going wrong? can you help me?
<!DOCTYPE html>
<html lang="en">
<head>
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap#4.3.1/dist/css/bootstrap.min.css"
/>
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.2/css/all.min.css"
/>
<style>
.dropdown-toggle::after {
display:none;
}
.task {
display: flex;
align-items: center;
justify-content: space-between;
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-12">
<div class="card-header">Todo List</div>
<div class="card-body">
<form>
<div class="input-group">
<input
type="text"
name="txtTaskName"
id="txtTaskName"
class="form-control"
/>
<button
type="button"
class="btn btn-primary"
id="btnAddNewTask"
>
Ekle
</button>
</div>
</form>
</div>
<div class="card mt-3">
<div class="card-header">
<button
class="btn btn-danger btn-sm float-sm-right"
id="btnDeleteTask"
>
Temizle
</button>
</div>
<ul class="list-group list-group-flush" id="task-list"></ul>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.bundle.min.js"></script>
<script>
dynamicList = [
{ Id: 1, gorevAdi: "Görev 1" },
{ Id: 2, gorevAdi: "Görev 2" },
{ Id: 3, gorevAdi: "Görev 3" },
];
displayTasks();
function displayTasks() {
let = ul = document.getElementById("task-list");
ul.innerHTML = "";
for (let index of dynamicList) {
let li = `
<li class="list-group-item task">
<div class="form-check">
<input type="checkbox" id="${index.Id}" class="form-check-input">
<label for="${index.Id}" class="form-check-label">${index.gorevAdi}</label>
</div>
<div class="dropdown">
<button class="btn btn-link dropdown-toggle" type="button" id="dropdownMenuButton1" data-bs-toggle="dropdown" aria-expanded="false">
<i class="fas fa-ellipsis-h"></i>
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenuButton1">
<li><a onclick = "deleteTask(${index.Id})" class="dropdown-item" href="#"><i class="fas fa-trash-alt"></i> Delelte</a></li>
<li><a class="dropdown-item" href="#"><i class="fas fa-pen"></i> Edit here</a></li>
</ul>
</div>
</li>`;
ul.insertAdjacentHTML("beforeend", li);
}
}
document
.querySelector("#btnAddNewTask")
.addEventListener("click", newTask);
document
.querySelector("#txtTaskName")
.addEventListener("keypress", function (event) {
if (event.key == "Enter") {
event.preventDefault();
document.getElementById("btnAddNewTask").click();
}
});
function newTask(event) {
let taskInput = document.querySelector("#txtTaskName");
if (taskInput.value == "") {
alert("Todo' ya bir içerik girmelisiniz.");
} else {
dynamicList.push({
Id: dynamicList.lenght + 1,
gorevAdi: taskInput.value,
});
taskInput.value = " ";
displayTasks();
}
event.preventDefault();
}
function deleteTask(id) {
let deletedId;
for (let i of dynamicList) {
if (i.id = id) {
deletedId = i
}
}
dynamicList.splice(deletedId, 1);
displayTasks()
}
</script>
</body>
</html>
In this section I add function that create tasks and togle menus on tasks
function displayTasks() {
let = ul = document.getElementById("task-list");
ul.innerHTML = "";
for (let index of dynamicList) {
let li = `
<li class="list-group-item task">
<div class="form-check">
<input type="checkbox" id="${index.Id}" class="form-check-input">
<label for="${index.Id}" class="form-check-label">${index.gorevAdi}</label>
</div>
<div class="dropdown">
<button class="btn btn-link dropdown-toggle" type="button" id="dropdownMenuButton1" data-bs-toggle="dropdown" aria-expanded="false">
<i class="fas fa-ellipsis-h"></i>
</button>
<ul class="dropdown-menu" aria-labelledby="dropdownMenuButton1">
<li><a onclick = "deleteTask(${index.Id})" class="dropdown-item" href="#"><i class="fas fa-trash-alt"></i> Delelte</a></li>
<li><a class="dropdown-item" href="#"><i class="fas fa-pen"></i> Edit here</a></li>
</ul>
</div>
</li>`;
ul.insertAdjacentHTML("beforeend", li);
}
}
In this section I create delete task function
}
function deleteTask(id) {
let deletedId;
for (let i of dynamicList) {
if (i.id = id) {
deletedId = i
}
}
dynamicList.splice(deletedId, 1);
displayTasks()
}

Want to add search result when search button is clicked

I am beginner in JavaScript. I am creating a project. Now i want to add a function when search button is clicked then search result display. However with the help of lecture i figure out how to filter when user is typing. But i want to add after typing in Search Bar when user click on search button then it also give the search result on same page same as it giving while typing.
showNotes();
// If user adds a note, add it to the localStorage
let addBtn = document.getElementById("addBtn");
addBtn.addEventListener("click", function (e) {
let addTxt = document.getElementById("addTxt");
let notes = localStorage.getItem("notes");
if (notes == null) {
notesObj = [];
} else {
notesObj = JSON.parse(notes);
}
notesObj.push(addTxt.value);
localStorage.setItem("notes", JSON.stringify(notesObj));
addTxt.value = "";
//console.log(notes)
showNotes();
});
// Function to show elements from localStorage
function showNotes() {
let notes = localStorage.getItem("notes");
if (notes == null) {
notesObj = [];
} else {
notesObj = JSON.parse(notes);
}
let html = "";
notesObj.forEach(function (element, index) {
html += `<div class="noteCard my-2 mx-2 card" style="width: 18rem;">
<div class="card-body">
<h5 class="card-title">Note ${index + 1}</h5>
<p class="card-text"> ${element}</p>
<button id="${index}"onclick="deleteNote(this.id)" class="btn btn-primary">Delete Note</button>
</div>
</div>`;
});
let notesElem = document.getElementById("notes");
if (notesObj.length != 0) {
notesElem.innerHTML = html;
} else {
notesElem.innerHTML = `Nothing to show`;
}
}
// function to delete a note
function deleteNote(index) {
let notes = localStorage.getItem("notes");
notesObj.splice(index, 1);
localStorage.setItem("notes", JSON.stringify(notesObj));
showNotes();
}
// search code
let search = document.getElementById('searchTxt');
search.addEventListener("input", function(){
let inputVal = search.value.toLowerCase();
// console.log('Input event fired!', inputVal);
let noteCards = document.getElementsByClassName('noteCard');
Array.from(noteCards).forEach(function(element){
let cardTxt = element.getElementsByTagName("p")[0].innerText;
if(cardTxt.includes(inputVal)){
element.style.display = "block";
}
else{
element.style.display = "none";
}
// console.log(cardTxt);
})
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Notes App</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<a class="navbar-brand" href="#">Magic Notes</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
</ul>
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" id="searchTxt" type="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" onclick="btnSearch()">Search</button>
</form>
</div>
</nav>
<div class="container my-3">
<h1>Welcome To Magic Notes</h1>
<div class="card">
<div class="card-body">
<h5 class="card-title">Add a note</h5>
<div class="form-group">
<textarea class="form-control" id="addTxt" rows="3"></textarea>
</div>
<button class="btn btn-primary" id="addBtn">Add Note</button>
</div>
</div>
<hr>
<h1>Your Notes</h1>
<hr>
<div id="notes" class="row container-fluid"> </div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
crossorigin="anonymous"></script>
<script src="app.js"></script>
</body>
</html>

How to test (unit test) arrow functions in JS via Jasmine?

I've done a small project "Notes" and now trying to test it using Jasmine. But since it's my first script using module style and imitation of the private functions, I can't understand how can I test the business logic of my script, since Jasmine doesn't see my arrow functions at all. Please help me to start my tests.
// eslint-disable-next-line func-names
const NotesList = ((function () {
const NOTE_TITLE = 'notesList';
const initNotesList = () => {
if (localStorage.getItem(NOTE_TITLE)) {
return JSON.parse(localStorage.getItem(NOTE_TITLE));
}
return [];
};
let notesList = initNotesList();
const saveData = (data) => {
notesList = [...data];
localStorage.setItem(NOTE_TITLE, JSON.stringify(notesList));
};
const addNote = (note) => {
if (notesList.includes(note)) {
return {
done: false,
error: 'The note is in the notes list already',
};
}
saveData([...notesList, note]);
return {
done: true,
};
};
const removeNote = (note) => {
const filteredNotesList = notesList.filter((item) => item !== note);
if (filteredNotesList.length === notesList.length) {
return {
done: false,
error: 'Note doesn\'t exist',
};
}
saveData(filteredNotesList);
return { done: true };
};
return {
getNotesList() {
return notesList;
},
addItem(item) {
return addNote(item);
},
removeItem(item) {
return removeNote(item);
},
};
})());
const STYLES = {
show: 'd-block',
};
const UI = {
noteValue: document.querySelector('#note-value'),
addNote: document.querySelector('#add-note'),
removeNote: document.querySelector('#remove-note'),
errorMessage: document.querySelector('#error-message'),
list: document.querySelector('#list'),
renderNotesList() {
this.clearNotesList();
NotesList.getNotesList().forEach((item) => {
const li = document.createElement('li');
li.innerText = item;
this.list.append(li);
});
},
clearNotesList() {
this.list.innerText = '';
},
handleNotesListResponse(result) {
if (result.done) {
this.noteValue.value = '';
this.errorMessage.classList.remove(STYLES.show);
this.renderNotesList();
} else {
this.errorMessage.innerText = result.error;
this.errorMessage.classList.add(STYLES.show);
}
},
};
UI.addNote.addEventListener('click', (event) => {
event.preventDefault();
const result = NotesList.addItem(UI.noteValue.value);
UI.handleNotesListResponse(result);
});
UI.removeNote.addEventListener('click', (event) => {
event.preventDefault();
const result = NotesList.removeItem(UI.noteValue.value);
UI.handleNotesListResponse(result);
});
UI.renderNotesList();
body{font-family:"Roboto Condensed",sans-serif;font-size:16px}header{background:none}.nav-link{font-size:20px}.container{max-width:1200px;background-image:url(../images/blue-snow.png)}.container-header{max-width:1200px}.container-footer{max-width:1200px}footer li{display:inline;padding-right:5px;padding-bottom:5px}ul li a :hover{transform:rotate(1turn);transition:0.5s ease-in}html{scroll-behavior:smooth}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
crossorigin="anonymous">
<link
href="https://fonts.googleapis.com/css?family=Roboto+Condensed&display=swap"
rel="stylesheet">
<link rel="stylesheet" type="text/css" href="../dist/style.css"/>
<title>Homework 1</title>
</head>
<body>
<div class="container-header mx-auto">
<header>
<nav class="navbar navbar-expand-lg navbar navbar-light bg-light">
<a class="navbar-brand pr-4"
href="https://github.com/TrekFuel/home_tasks_FE-2" target="_blank"><img
src="../images/github-logo-header-image.png"
alt="GitHub" title="GitHub"
width="40" height="40"/></a>
<button class="navbar-toggler" type="button" data-toggle="collapse"
data-target="#navbarSupportedContent"
aria-controls="navbarSupportedContent" aria-expanded="false"
aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active pr-5">
<a class="nav-link" href="homework-3.html">Home Tasks (to the
previous page)<span
class="sr-only"></span></a>
</li>
<li class="nav-item active">
<a class="nav-link" href="#2">Contacts<span
class="sr-only"></span></a>
</li>
</ul>
</div>
</nav>
</header>
</div>
<div class="container mx-auto d-flex">
<main>
<div class="row mt-5 mb-5 ml-3 mr-3">
<div class="col">
<h1 class="text-center mb-4">Notes</h1>
<div class="input-group input-group-lg mx-auto mt-5 mb-5">
<input type="text" class="form-control"
id="note-value"
name="note-value"
value=""
placeholder="Note"
aria-label="Note"
aria-describedby="button-addon4 inputGroup-sizing-lg">
<div class="input-group-append" id="button-addon4">
<button class="btn btn-outline-secondary" id="add-note"
type="button">Add note
</button>
<button class="btn btn-outline-secondary" id="remove-note"
type="button">Remove
note
</button>
</div>
</div>
<div class="alert alert-danger d-none" id="error-message"
role="alert"></div>
</div>
</div>
<div class="row mt-3 mb-3">
<div class="col">
<ul id="list"></ul>
</div>
</div>
</main>
</div>
<div class="container-footer mx-auto">
<footer>
<a name="2"></a>
<div class="card text-center">
<div class="card-header">
<a name="7"></a>
<h3>Contacts</h3>
</div>
<div class="card-footer text-center">
<ul class="list-unstyled p-2">
<li>
<a href="https://vk.com/bolotinnikita" target="_blank">
<img src="../images/vk-logo.png"
width="30"
height="30"
alt="ВК"
title="ВК"/></a>
</li>
<li>
<a href="https://twitter.com/bolotinnick" target="_blank">
<img src="../images/twitter-logo.png"
width="30"
height="30"
alt="Twitter"
title="Twitter"/></a>
</li>
<li>
<a href="https://www.linkedin.com/in/bolotinnick/" target="_blank">
<img src="../images/linkedin-logo.png"
width="30"
height="30"
alt="LinkedIn"
title="LinkedIn"/></a>
</li>
<li>
<a href="https://github.com/TrekFuel" target="_blank">
<img src="../images/github-logo.png"
width="30"
height="30"
alt="GitHub"
title="GitHub"/></a>
</li>
<li>
<a href="https://www.instagram.com/bolotinnick/" target="_blank">
<img src="../images/instagram-logo.png"
width="30"
height="30"
alt="Instagram"
title="Instagram"/></a>
</li>
<li>
<a href="mailto:ridge96#yandex.ru?subject=website">
<img src="../images/email-logo.png"
width="30"
height="30"
alt="Email"
title="Email"/></a>
</li>
<li>
<a href="https://t.me/bolotinnick" target="_blank">
<img src="../images/telegram-logo.png"
width="30"
height="30"
alt="Telegram"
title="Telegram"/></a>
</li>
<li>
<a href="skype:nick-spinner96?add">
<img src="../images/skype-logo.png"
width="30"
height="30"
alt="Skype"
title="Skype"/></a>
</li>
<li>
<a href="viber://chat?number=+375291328633">
<img src="../images/viber-logo.png"
width="30"
height="30"
alt="Viber"
title="Viber"/></a>
</li>
<li>
<a href="https://wa.me/375291328633" target="_blank">
<img src="../images/whatsapp-logo.png"
width="30"
height="30"
alt="WhatsApp"
title="WhatsApp"/></a>
</li>
</ul>
<div class="btn btn-info mb-2">Bolotin Nikita ©, 2019-2020 <br>
FE-2
Courses
</div>
</div>
<div class="text-left m-2">
<a href="#top" class="btn btn-primary" id="btn">To the top
↑</a>
</div>
</div>
</footer>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin="anonymous"></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
crossorigin="anonymous"></script>
<script
src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
crossorigin="anonymous"></script>
<script src="../js/notes(hw-3).js"></script>
</body>
</html>
// eslint-disable-next-line no-undef
describe('notes(hw-3).js -> initNotesList', () => {
// eslint-disable-next-line no-undef
it('should return Object from the LocalStorage in case there are items'
+ ' there, otherwise should return an empty array', () => {
});
});
What exactly are you looking to test that you can't already test? The getNotesList, addItem, removeItem methods are already exposed. Just simply test the exposed, public functions directly. This will indirectly test all of the implementation details.
Now, it might be that there is some bit of the code that is not testable through this manner, or it is extremely awkward to test. In this case, you should refactor your code to make it more testable.
For example, the initNotesList function is not directly testable. You may want to expose this as a public function (ie- add it to the return statement) and write some unit tests against it. I would also create and expose a clearNotesList function to aid in the set up and tear down of tests.
But other than that, there's not much to do. There's no magic to unit testing. You just need to create clear, simple code and expose the proper pieces to make testing easy.

open modal when condition is true- Javascript and bootstrap

I need a button that opens up a module in bootstrap when condition is true
User inputs his btc address and than i check if its a valid btc address- if it is valid an modal should open and display the user a receiving address.
When the user input =! a btc address the modal should stay closed.
The code for checking the Btc address works- all i need is to hook up the result to my button.
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>BItmixxer</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<style media="screen">
hr.style1{
border-top: 1px solid #8c8b8b;
}
</style>
</head>
<body>
<nav class="navbar navbar-expand-md bg-dark navbar-dark">
<!-- Brand -->
<a class="navbar-brand" href="#">Navbar</a>
<!-- Toggler/collapsibe Button -->
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
<span class="navbar-toggler-icon"></span>
</button>
<!-- Navbar links -->
<div class="collapse navbar-collapse" id="collapsibleNavbar">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
</ul>
</div>
</nav>
<div class="jumbotron jumbotron-fluid" style="text-align:center" >
<div class="container">
<h1>Crypto BItmixxer</h1>
<p>some more Text about rypto mixxer</p>
</div>
</div>
<div class="container" style="text-align:center" >
<h1>BTC MIxxer</h1>
<p>Choose COins to mix:</p> <button type="button" class="btn btn-outline-primary">Bitcoin</button>
<button type="button" class="btn btn-outline-success">Ethereum</button>
<br>
<br>
<br>
<div class="form-group" id="elMessage" class="msg">
<input type="text" class="form-control" id="inpAddress" value="">
</div>
<button type="button" class="btn btn-primary" id="btnValidate" data-toggle="modal" data-target="#myModal">Next</button>
<script>
var normalize = (s) => {
let x = String(s) || '';
return x.replace(/^[\s\xa0]+|[\s\xa0]+$/g, '');
};
var check = (s) => {
if (s.length < 26 || s.length > 35) {
return false;
}
let re = /^[A-Z0-9]+$/i;
if (!re.test(s)) {
return false;
}
return true;
};
var getEl = (id) => {
return document.getElementById(id) || null;
};
var elMessage = getEl('elMessage');
var inpAddress = getEl('inpAddress');
var btnValidate = getEl('btnValidate');
var lnkClear = getEl('lnkClear');
var setMessage = (txt = '', clss = 'msg') => {
elMessage.className = clss;
elMessage.innerHTML = txt;
};
var validate = (s) => {
let className = 'msg fail';
let textMessage = 'Invalid bitcoin address';
if (!s) {
textMessage = 'Please enter a valid address';
}
let re = check(s);
if (re) {
className = 'msg pass';
textMessage = 'Bitcoin address is valid';
}
setMessage(textMessage, className);
return re;
};
btnValidate.onclick = () => {
let v = normalize(inpAddress.value);
let result = validate(v);
if (result) {
inpAddress.value = v;
}
};
lnkClear.onclick = () => {
inpAddress.value = '';
inpAddress.focus();
setMessage('Enter any text and press "Validate"');
};
</script>
</div>
<!-- The Modal -->
<div class="modal" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Modal Heading</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
<h3>Please send your BTC(min0.5) to</h3>
<p id ="btc-house" style="color:blue;"></p>
<script>
var myArray = ['1QFsuDg4HyCJZFBfC2ivxHCK2CX2i9YvWN', ' 1EhfSjMuyAyrpRRGf5sSCU3YDbVAqjJNxH', '1N2e39vyTrk6HtvZPqWPrHfHKBzsnQNN4V','1GVSGZxwU69fN5oPprSxXRnjsZPvo8bGw3'];
var rand = myArray[Math.floor(Math.random() * myArray.length)];
document.getElementById("btc-house").innerHTML = rand;
</script>
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</body>
</html>
The Bootstrap modal can be opened using JS (https://getbootstrap.com/docs/4.0/components/modal/#via-javascript)
For that to work you have to remove the data-attributes from your button, and place the opening code in your JavaScript.
Note: I had to modify your code a bit, so it worked error-free as a snippet.
var normalize = (s) => {
let x = String(s) || '';
return x.replace(/^[\s\xa0]+|[\s\xa0]+$/g, '');
};
var check = (s) => {
if (s.length < 26 || s.length > 35) {
return false;
}
let re = /^[A-Z0-9]+$/i;
if (!re.test(s)) {
return false;
}
return true;
};
var getEl = (id) => {
return document.getElementById(id) || null;
};
var elMessage = getEl('elMessage');
var inpAddress = getEl('inpAddress');
var btnValidate = getEl('btnValidate');
var lnkClear = getEl('lnkClear');
var setMessage = (txt = '', clss = 'msg') => {
elMessage.className = clss;
elMessage.innerHTML = txt;
};
var validate = (s) => {
let className = 'msg fail';
let textMessage = 'Invalid bitcoin address';
if (!s) {
textMessage = 'Please enter a valid address';
}
let re = check(s);
if (re) {
className = 'msg pass';
textMessage = 'Bitcoin address is valid';
}
setMessage(textMessage, className);
return re;
};
btnValidate.onclick = () => {
let v = normalize(inpAddress.value);
let result = validate(v);
if (result) {
inpAddress.value = v;
// You have the modal with open it with JS
$('#myModal').modal('show')
}
};
/*lnkClear.onclick = () => {
inpAddress.value = '';
inpAddress.focus();
setMessage('Enter any text and press "Validate"');
};*/
var myArray = ['1QFsuDg4HyCJZFBfC2ivxHCK2CX2i9YvWN', ' 1EhfSjMuyAyrpRRGf5sSCU3YDbVAqjJNxH', '1N2e39vyTrk6HtvZPqWPrHfHKBzsnQNN4V', '1GVSGZxwU69fN5oPprSxXRnjsZPvo8bGw3'];
var rand = myArray[Math.floor(Math.random() * myArray.length)];
document.getElementById("btc-house").innerHTML = rand;
hr.style1 {
border-top: 1px solid #8c8b8b;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<nav class="navbar navbar-expand-md bg-dark navbar-dark">
<!-- Brand -->
<a class="navbar-brand" href="#">Navbar</a>
<!-- Toggler/collapsibe Button -->
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
<span class="navbar-toggler-icon"></span>
</button>
<!-- Navbar links -->
<div class="collapse navbar-collapse" id="collapsibleNavbar">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Link</a>
</li>
</ul>
</div>
</nav>
<div class="jumbotron jumbotron-fluid" style="text-align:center">
<div class="container">
<h1>Crypto BItmixxer</h1>
<p>some more Text about rypto mixxer</p>
</div>
</div>
<div class="container" style="text-align:center">
<h1>BTC MIxxer</h1>
<p>Choose COins to mix:</p> <button type="button" class="btn btn-outline-primary">Bitcoin</button>
<button type="button" class="btn btn-outline-success">Ethereum</button>
<br>
<br>
<br>
<div class="form-group" id="elMessage" class="msg">
<input type="text" class="form-control" id="inpAddress" value="">
</div>
<button type="button" class="btn btn-primary" id="btnValidate">Next</button>
</div>
<!-- The Modal -->
<div class="modal" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Modal Heading</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
<h3>Please send your BTC(min0.5) to</h3>
<p id="btc-house" style="color:blue;"></p>
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>

Categories

Resources