Pushing values into an array - javascript

When a value(person) is entered, the code create a <li> with the name of it. Multiple names, multiple <li>. I would also like to push all the values into people for future use.
const addForm = document.querySelector('.add');
const list = document.querySelector('.todos');
let people
const generateTemplate = todo => {
const html = `
<li>
<span>${todo}</span>
<i class="far fa-trash-alt delete"></i>
</li>`
list.innerHTML += html;
}
addForm.addEventListener('submit', e => {
const todo = addForm.add.value.trim();
e.preventDefault();
if (todo.length) {
if (people === null) {
people = [];
}
people.push(todo);
console.log(people)
}
generateTemplate(todo);
addForm.reset();
people.push(todo)
console.log(people)
});
<!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">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
<title>Todolist</title>
</head>
<body>
<form action="" class="add">
<h1>Group generator</h1>
<input type="text" id="name" name="add" placeholder="Enter name here">
<input type="submit" value="submit them">
<p>you can also press enter instead</p>
</form>
<ul class="todos">
</ul>
</body>
</html>

Instead of people===null use if (!people), because people is undefined at first time:
if (!people) {
people = [];
}
<!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">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
<title>Todolist</title>
</head>
<body>
<form action="" class="add">
<h1>Group generator</h1>
<input type="text" id="name" name="add" placeholder="Enter name here">
<input type="submit" value="submit them"> <p>you can also press enter instead</p>
</form>
<ul class="todos">
</ul>
<script>
const addForm = document.querySelector('.add');
const list = document.querySelector('.todos');
let people
const generateTemplate = todo => {
const html = `
<li>
<span>${todo}</span>
<i class="far fa-trash-alt delete"></i>
</li>`
list.innerHTML += html;
}
addForm.addEventListener('submit', e => {
debugger
const todo = addForm.add.value.trim();
e.preventDefault();
if (todo.length) {
if (!people) {
people = [];
}
people.push(todo);
console.log(people)
}
generateTemplate(todo);
addForm.reset();
people.push(todo)
console.log(people)
});
</script>
</body>
</html>

Related

how to make list with for loop?

I tried to made a list with a for Loop and now I'm stuck because the program isn't showing any error but is not building any list elements. Can somebody explain why and how?
It seems that it can read the value of the input element which I thought don`t seems to be the problem, so I was thinking that it must be the problem with reading it from the array. But I am just a beginner so when someone knows the actual solution to the problem, I would appreciate it.
let array = [];
function buildList() {
let ul = document.getElementById("prototype_List");
ul.innerHTML = "";
for (i = 0; i < array.length; i++) {
let list = document.createElement("li");
list.innerText = array[i];
let setting = document.getElementById("prototype_List");
setting.append(list);
}
}
function Name_Tag() {
let checkName = document.getElementById("textfeld").value;
if(checkName.length === 0) {
alert("write Name");
} else {
array.push(checkName);
buildList();
}
}
<!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">
<script src="test.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<title>Document</title>
</head>
<body>
<div class="container">
<div class="input-group mb-3">
<button onclick="Name_Tag" class="btn btn-outline-secondary" type="button" id="button-addon1">ADD Name</button>
<input id="textfeld" type="text" class="form-control" placeholder="" aria-label="Example text with button addon" aria-describedby="button-addon1">
</div>
<ul id="prototype_List">
</ul>
</div>
</body>
</html>

script.js:23 Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')

I have 3 html files for this page. index.html, positive review page and negative review page. I already have my JavaScript redirected to the right pages after clicking the emojis feedback and then the button. After clicking the button depending on the emojis clicked it redirects to the negative review page, if the emoji selected is neutral or unhappy and, if the emoji selected is satisfied it redirects to the positive review page. I am now stuck with subject line error in the console. The below is my Javascript file, followed by index.html file. Kindly assist me, thanks in advance.
const sendButton = document.querySelector("#send");
const panelContainer = document.querySelector(".panel-container");
const ratings = document.querySelectorAll(".rating");
const experience = document.querySelectorAll(".active small");
const removeActive = () => {
for (let i = 0; i < ratings.length; i++) {
ratings[i].classList.remove("active");
}
};
panelContainer.addEventListener("click", (e) => {
if (e.target.parentNode.classList.contains("rating")) {
removeActive();
e.target.parentNode.classList.add("active");
}
});
sendButton.addEventListener("click", () => {
const experience = document.querySelector(".active small");
console.log(experience);
if (
experience.innerHTML === "Unhappy" ||
experience.innerHTML === "Neutral"
) {
window.location = "negative_review.html";
} else {
window.location = "positive_review.html";
}
});
index.html
<!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" />
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css"
/>
<link rel="stylesheet" href="style.css" />
<title>Feedback</title>
</head>
<body>
<div id="panel" class="panel-container">
<h2>Welcome Text</h2>
<strong
>How was your experience <br />
with us?
</strong>
<div class="ratings-container">
<div class="rating">
<img
src="https://cdn-icons-png.flaticon.com/128/742/742752.png"
alt=""
/>
<small>Unhappy</small>
</div>
<div class="rating">
<img
src="https://cdn-icons-png.flaticon.com/128/725/725085.png"
alt=""
/>
<small>Neutral</small>
</div>
<div class="rating active">
<img
src="https://cdn-icons-png.flaticon.com/128/166/166549.png"
alt=""
/>
<small>Satisfied</small>
</div>
</div>
<form>
<label for="feedback">Please Tell Us About Your Experience</label>
<textarea name="" id="" maxlength="350" cols="30" rows="10"></textarea>
</form>
<button class="btn" id="send">Send Review</button>
</div>
<script src="script.js"></script>
</body>
</html>
negative review. html
<!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" />
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css"
/>
<link rel="stylesheet" href="style.css" />
<title>Feedback</title>
</head>
<body>
<div id="panel" class="panel-container">
<!-- <form> -->
<strong>Thank you!</strong> <i class="fa-solid fa-heart"></i>
<br/>
<br/>
One of our team members will review your comments <br />
and reach out to you to resolve any issues.
<!-- </form> -->
</div>
<script src="script.js"></script>
</body>
</html>
On the negative review page, there isn't a button with the id send, so your querySelector call in line 1 returns null. To fix this, you should conditionally add an event listener like so:
if (sendButton !== null) {
sendButton.addEventListener("click", () => {
const experience = document.querySelector(".active small");
console.log(experience);
if (
experience.innerHTML === "Unhappy" ||
experience.innerHTML === "Neutral"
) {
window.location = "negative_review.html";
} else {
window.location = "positive_review.html";
}
});
}

How to copy the input text on button click?

I am looking to copy the text written in an input when the user click on a button. How can I do it ?
Here is my HTML structure :
<!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>2b2tyoung.tk</title>
<link rel="stylesheet" href="style.css">
<script src="main.js"></script>
</head>
<body>
<div class="container">
<div label>
Join server
</div>
<div class="copy-text">
<input type="text" class="text" value="2b2tyoung.tk">
<button>
<i class="fa fa-clone"></i>
</button>
</div>
</div>
</body>
</html>
Here I selected the fa-clone icon, added a listener on click, then I copied the value of the input.
document.querySelector(".fa-clone").addEventListener("click", () => {
let input = document.querySelector(".copy-text input");
navigator.clipboard.writeText(input.value);
console.log("copied "+input.value)
})
<div class="copy-text">
<input type="text" class="text" value="2b2tyoung.tk">
<button>
<i class="fa fa-clone">Clone</i>
</button>
</div>
<!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>2b2tyoung.tk</title>
<link rel="stylesheet" href="style.css" />
<script src="main.js"></script>
</head>
<body>
<div class="container">
<div label>Join server</div>
<div class="copy-text">
<input type="text" class="text" value="2b2tyoung.tk" />
<button onclick="copyInputValue()">
<i class="fa fa-clone"></i>
</button>
</div>
</div>
</body>
</html>
<script>
function copyInputValue() {
const ipt = document.querySelector("#app input");
ipt.select();
const copyed = document.execCommand("copy");
if (copyed) {
alert("copy success!");
} else {
alert("copy failed!");
}
}
</script>

values from input box is not saving on localstorage

i have develop a todo app. where user insert some values and it gets save on the screen. now i want to save the values into localstorage.but its not getting saved instead i am getting a empty {}.
here is the javascript code
//crete element from input box and delete
let knoo = document.getElementById('kno')
let box= document.getElementById('txt')
let sub= document.getElementById('sub').addEventListener('click',()=>{
let para = document.createElement('ul')
para.innerText= box.value
knoo.appendChild(para)
box.value=''
localStorage.setItem('key', JSON.stringify(para))
//styling
para.addEventListener('click', ()=>{
para.style.textDecoration = 'line-through'
})
//delete
para.addEventListener('dblclick', ()=>{
knoo.removeChild(para)
})
})
here is the html
<!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>Document</title>
</head>
<body>
<h2>hi</h2>
<div id="hello">
<h1>hello</h1>
</div>
<button id="btn">delete</button> <br>
<br>
<input type="text" id="txt">
<button type="submit" id="sub">+</button>
<div id="kno"></div>
<script src="main.js"></script>
</body>
</html>
That is because you use JSON.stringify with a html element which will not work and it will always produce {}.
The JSON.stringify() method converts a JavaScript object or value to a JSON string
I solution is to use array to store the value for para and use JSON.stringify for the array
let knoo = document.getElementById('kno')
let box= document.getElementById('txt')
let storedvalue = []
if(localStorage.getItem('key')){
storedvalue = localStorage.getItem('key');
}
let sub= document.getElementById('sub').addEventListener('click',()=>{
let para = document.createElement('ul')
para.innerText= box.value
knoo.appendChild(para)
box.value=''
storedvalue.push(para.innerText)
localStorage.setItem('key', JSON.stringify(storedvalue))
//styling
para.addEventListener('click', ()=>{
para.style.textDecoration = 'line-through'
})
//delete
para.addEventListener('dblclick', ()=>{
knoo.removeChild(para)
})
})
<!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>Document</title>
</head>
<body>
<h2>hi</h2>
<div id="hello">
<h1>hello</h1>
</div>
<button id="btn">delete</button> <br>
<br>
<input type="text" id="txt">
<button type="submit" id="sub">+</button>
<div id="kno"></div>
<script src="main.js"></script>
</body>
</html>

Local Storage on a to do list

This is a typical todo list. Items can be added or removed,it works like this but unfortunately when I refresh it disappears. I wanted to use the localStorage functionality to solve the issue. I managed to create an array where to store the items. Now I want to show in the browser the items stored in tasks. I've got stuck when I load document.addEventListener('DOMContentLoaded', getTasks) and in particular getTasks(). I have set console.log('bonjour'), to test it and it does not go through.
Thank you, as always
function getTasks() {
console.log('bonjour')
let tasks;
if(localStorage.getItem('tasks') === null) {
tasks = [];
} else {
tasks = JSON.parse(localStorage.getItem('tasks'));
}
tasks.forEach(task => {
const html = `
<li>
<span>${task}</span>
<i class="far fa-trash-alt delete"></i>
</li>`
list.innerHTML += html;
console.log('hi')
});
}
<!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">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
<title>Todolist</title>
</head>
<body>
<form action="" class="add">
<h1>To do list</h1>
<input type="text" id="name" name="add" placeholder="Enter name here">
</form>
<ul class="todos">
<li>
<span>marco</span>
<i class="far fa-trash-alt delete"></i>
</li>
</ul>
<script src="app.js"></script>
</body>
</html>
function getTasks() {
console.log('bonjour')
let tasks
if (localStorage.getItem('tasks') === null) {
tasks = []
} else {
tasks = JSON.parse(localStorage.getItem('tasks'))
}
let list = document.getElementById('theList')
tasks ? .forEach((task) => {
const html = `
<li>
<span>${task}</span>
<i class="far fa-trash-alt delete"></i>
</li>`
list.innerHTML += html
console.log('hiiiii')
})
}
function storeValue(val) {
if (!val) return
if (!localStorage.getItem('tasks')) {
let tasks = []
tasks.push(val)
localStorage.setItem('tasks', JSON.stringify(tasks))
getTasks()
} else {
let tasks = JSON.parse(localStorage.getItem('tasks'))
tasks.push(val)
localStorage.setItem('tasks', JSON.stringify(tasks))
getTasks()
}
}
getTasks()
<!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">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
<title>Todolist</title>
</head>
<body>
<!-- <form action="" class="add"> -->
<h1>To do list</h1>
<input type="text" id="name" name="add" placeholder="Enter name here" onchange="storeValue(this.value)">
<!-- </form> -->
<ul class="todos" id="theList">
<li>
<span>marco</span>
<i class="far fa-trash-alt delete"></i>
</li>
</ul>
<script src="app.js"></script>
</body>
</html>
here is the solution try it on your local system here you will get an error so it is better to test on your own system. Also clean up the code I just resolved the issue

Categories