Input Value showing as undefined - javascript

I'm fairly new to javascript and trying to make a simple To Do list work. I have the basic functionality down, but I'm trying to understand why the input value in my code is returning undefined?
The remove button adds just fine, so I know the function is working.
<!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="css/main.css" />
<title>To Do List</title>
</head>
<body>
<div class="content__container">
<div class="list__container">
<div class="header__container">
<h1 class="header__title">TO DO LIST</h1>
<input id="header__input" type="text" />
<button class="header__button">Add</button>
</div>
<div class="list__content"></div>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
const btn = document.querySelector(".header__button");
const listContent = document.querySelector(".list__content");
let input = document.getElementById("header__input").value;
function addItem() {
const toDoItem = document.createElement("li");
const text = document.createTextNode(input);
const remove = document.createElement("button");
remove.textContent = "remove";
remove.classList.add("list__remove");
toDoItem.classList.add("list__items");
toDoItem.appendChild(text);
toDoItem.appendChild(remove);
listContent.appendChild(toDoItem);
}
btn.addEventListener("click", addItem);

Your script is getting the input value only when it start and not when the function is called.
const btn = document.querySelector(".header__button");
function addItem() {
const listContent = document.querySelector(".list__content");
let input = document.getElementById("header__input").value;
const toDoItem = document.createElement("li");
const text = document.createTextNode(input);
const remove = document.createElement("button");
remove.textContent = "remove";
remove.classList.add("list__remove");
toDoItem.classList.add("list__items");
toDoItem.appendChild(text);
toDoItem.appendChild(remove);
listContent.appendChild(toDoItem);
}
btn.addEventListener("click", addItem);
Moving listContent and the input variable into the function will ensure that you get the values ​​every time the function is executed.

Related

trying to display an array of object on my screen in vanilla javascript

please i am new to javaScript. i am trying to display the items inside of the data array on my screen after i click on the add task button. i can the data inside my console but when i loop over it and try and render it on my screen i get this error Uncaught TypeError: Cannot read properties of null
<!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="./index.css">
<title>Document</title>
</head>
<body>
<div class="container">
<input id="nameInput" placeholder="enter name" >
<input id="jobInput" placeholder="enter job" >
<input id="taskInput" placeholder="enter task" >
<button id="addBtn">Add Task</button>
<div class="items"></div>
</div>
<script src="./index.js"></script>
</body>
</html>
const data = [];
const list = document.createDocumentFragment();
const nameEl = document.getElementById("name");
const jobEl = document.getElementById("job");
const task = document.getElementById("task");
const itemsEl = document.getElementById("items")
const addBtn = document.getElementById("addBtn");
const deleteBtn = document.getElementById("deleteBtn");
function addItem(){
const name = document.getElementById("nameInput").value;
const job = document.getElementById("jobInput").value;
const task = document.getElementById("taskInput").value;
data.push({ name, job, task });
displayData(data)
}
function displayData(data){
console.log(data)
data.map(({ name, job, task }) => {
const item = `
<h1 id="name" class="name">${name}</h1>
<h3 id="job" class="job">${job}</h3>
<h4 id="task" class="task">${task}</h4>
<button id="deleteBtn">Delete Task</button>
`
const items = document.createElement("div");
items.innerHTML = item;
list.appendChild(items)
})
itemsEl.appendChild(list)
}
addBtn.addEventListener("click", () => {
addItem()
})
I have tried looping over the array of object but i am getting undefined.
You tried to select the 'items' div with:
const itemsEl = document.getElementById("items")
But you div doesn't have an id. You could add an id or you could:
const itemsEl = document.getElementsByClassName("items")[0]

Cannot read properties of null (reading 'addEventListener') when trying to console.log the value of the html input tag when btn click

I'm trying to create a make addEventListener function to a button, when click it should print the value of the input.
but I'm getting an error message:
Cannot read properties of null (reading 'addEventListener')
let plus = document.getElementById('btnPlus');
let minus = document.getElementById('btnMinus');
let multiplay = document.getElementById('btnMultiplay');
let divide = document.getElementById('btnDivide');
let inputOne = document.getElementById('firstNum');
let inputTwo = document.getElementById('secondNum');
// if + button click display in result inputOne + inputTwo
plus.addEventListener('click', function() {
let valueOne = inputOne.value;
let valueTwo = inputTwo.value;
console.log(valueOne);
});
<!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>Calcultaor</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="mainHeader">
<h1> Calculator </h1>
<label for="">Enter First Number</label>
<input type="text" class="firstNum"> <br/>
<label for="">Enter Second Number</label>
<input type="text" class="secondNum"><br/>
<button class="btnPlus">+</button>
<button class="btnMinus">-</button>
<button class="btnMultiplay">*</button>
<button class="btnDivide">/</button>
<h2> The Result Is <span class=span_result /> </h2>
</div>
<script src="app.js"></script>
</body>
</html>
getElementById works only with ID not with classes. Review your HTML
Because this code does not contain an id
<button class="btnPlus">+</button>
If you want get an element by id, the element must contain the id.
Try this
<button id="btnPlus">+</button>
The addEventListener() method attaches an event handler to an element.
You don't have an element with id btnPlus.
Now the below code is running fine.
You have to define the variable as a Number.
<!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>
<div class="mainHeader">
<h1>Calculator</h1>
<label for="">Enter First Number</label>
<input type="text" id="firstNum" /> <br />
<label for="">Enter Second Number</label>
<input type="text" id="secondNum" /><br />
<button id="btnPlus">+</button>
<button id="btnMinus">-</button>
<button id="btnMultiplay">*</button>
<button id="btnDivide">/</button>
<h2>The Result Is <span id="span_result" /></h2>
</div>
<p id="demo">
<script>
let plus = document.getElementById("btnPlus");
let minus = document.getElementById("btnMinus");
let multiplay = document.getElementById("btnMultiplay");
let divide = document.getElementById("btnDivide");
let inputOne = document.getElementById("firstNum");
let inputTwo = document.getElementById("secondNum");
const element = plus;
element.addEventListener("click", function(){
let valueOne = inputOne.value;
let valueTwo = inputTwo.value;
let sum = Number(valueOne)+ Number(valueTwo)
console.log(sum);
document.getElementById("span_result").innerHTML =sum
});
const element2 = minus;
element2.addEventListener("click", function(){
let valueOne = inputOne.value;
let valueTwo = inputTwo.value;
let sum = Number(valueOne)- Number(valueTwo)
console.log(sum);
document.getElementById("span_result").innerHTML =sum
});
const element3 = multiplay;
element3.addEventListener("click", function(){
let valueOne = inputOne.value;
let valueTwo = inputTwo.value;
let sum = Number(valueOne)* Number(valueTwo)
console.log(sum);
document.getElementById("span_result").innerHTML =sum
});
const element4 = divide;
element4.addEventListener("click", function(){
let valueOne = inputOne.value;
let valueTwo = inputTwo.value;
let sum = Number(valueOne)/ Number(valueTwo)
console.log(sum);
document.getElementById("span_result").innerHTML =sum
});
</script>
</p>
</body>
</html>

Problem with targeting created button with addEventListener

I'm learning vanilla JS and trying to make "To-do list" project.
So, idea is simple adding values from form into the list. After that I add edit/remove buttons for every li in list and put the addEventListener to that buttons.
For some reason, event listener is targeted on button from form. When I click on button to add new item in list, there is click listener that I want on edit button.
I try different ways to target the right button with parentNodes or childNodes, i find the pretty same code as mine but that don't work for me.
function newItem() {
let input = document.getElementById("input").value;
if (input != "") {
let li = document.createElement("li");
li.appendChild(document.createTextNode(input));
let editButton = document.createElement("button");
editButton.appendChild(document.createTextNode("Edit"));
li.appendChild(editButton);
editButton.addEventListener("click", console.log('a'));
let ul = document.getElementById("list");
ul.appendChild(li);
document.getElementById("input").value = "";
}
function editItem() {
alert('e');
}
}
<!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>To Do!</title>
</head>
<body>
<h1>To do list</h1>
<div>
<input id = "input" type = "text" placeholder="What do you want to do?" value="">
<button id = "enter" onclick = "newItem()">Ok</button>
</div>
<p id="proba"></p>
<div>
<ul id = "list">
</ul>
</div>
<script type="text/javascript" src="todo.js"></script>
</body>
</html>
You need to pass a function in addEventListener, not just code.
editButton.addEventListener("click", ()=>{console.log('a')});
Or pass it to editItem
editButton.addEventListener("click", editItem);
addEventListener takes in a string and a callback function, by passing in console.log('a'), JavaScript is passing in the return value of the console.log, which is undefined. You instead need to wrap it in a function like this: editButton.addEventListener('click', () => { console.log('a'); }).
You will need to pass a function to your addEventListener method like this: editButton.addEventListener("click", editItem).
Remember that you don't have to add the parameter on the parenthesis of your function.
You can also invoke an anonymous function like this and then add your function to the right block:
editButton.addEventListener("click", () => editItem()).
function newItem() {
let input = document.getElementById("input").value;
if (input != "") {
let li = document.createElement("li");
li.appendChild(document.createTextNode(input));
let editButton = document.createElement("button");
editButton.appendChild(document.createTextNode("Edit"));
li.appendChild(editButton);
editButton.addEventListener("click", () => editItem());
let ul = document.getElementById("list");
ul.appendChild(li);
document.getElementById("input").value = "";
}
function editItem() {
alert('e');
}
}
<!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>To Do!</title>
</head>
<body>
<h1>To do list</h1>
<div>
<input id = "input" type = "text" placeholder="What do you want to do?" value="">
<button id = "enter" onclick = "newItem()">Ok</button>
</div>
<p id="proba"></p>
<div>
<ul id = "list">
</ul>
</div>
<script type="text/javascript" src="todo.js"></script>
</body>
</html>

todos list with a saved array and then retrieve it stuck?

i started an app todoslist , after creating first code simply of adding new todos in DOM
now my task is this :
addtodo :
// grab todo value
// pu tit in the array
// tell the draw method to redraw the todos
drawtodo :
grab the array
for each text add a todo entry in the documen
the array
my html 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">
<link rel="stylesheet" type="text/css" href="style.css">
<title>TodoList</title>
</head>
<body>
<div class="todolist_box">
<h3> To Do List </h3>
<div class="input">
<input type="text" id ="inp" placeholder="Add new Task">
<button onclick="newTodo()" ><i> enter </i></button>
<button onclick="newTodo()" ><i> save </i></button>
<button onclick="drawtodo()" ><i> load </i></button>
</div>
<ul id="myUL">
</ul>
</div>
<script src="script.js" type="application/javascript"></script>
</body>
</html>
and this is my javascript code
function newElement() {
// this code doesn't work, but it gives you an idea
const li = document.createElement("li")
const newEntry = document.getElementById("inp").value
const u = document.createTextNode(newEntry)
li.appendChild(u)
document.getElementById("myUL").appendChild(li)
document.getElementById("inp").value = "Nothing"
// something like thi
let todos = []
function newTodo() {
let inpvalue = document.getElementById('inp').value
todos.push(inpvalue)
// trigger draw event
}
function drawtodo() {
for (var i = todos.length - 1; i >= 0; i--) {
let li = document.createElement('li')
let newlist = li.appendChild(document.createTextNode(todos[i]))
inpvalue.appendChild(newlist)
}
}
document.onload = function() {
// this will excute when the document loads
}
}
Try using Javascript event listener instead of onclick attribute in html.
HTML:
<button id="load" ><i> load </i></button> // Removed onclick attribute
JS:
document.getElementById("load").addEventListener("click", drawtodo, false);
same with enter and save buttons, when click triggers the newTodo function.

input field won't clear up

I can't clear up my input field even tho i followed a tutorial step by step , i'm making this to do list and I want the input field to be clear anytime i submit a new to do . so what is wrong with my code ?
ps : i tried to clear the cache and nothing
let addButton=document.getElementById('addButton');
let toDoContainer = document.getElementById('ToDoContainer');
let inputField = document.getElementById('text');
//event listeners
addButton.addEventListener('click',addTodo);
//functions
function addTodo(event,title){
event.preventDefault();
//create the to do
let toDoDiv = document.createElement('div');
toDoDiv.classList.add('todo');
const newToDo =document.createElement('p');
newToDo.innerHTML=inputField.value;
newToDo.classList.add('todo-item');
toDoDiv.appendChild(newToDo);
toDoContainer.appendChild(toDoDiv);
//check mark button
const completedButton = document.createElement('button');
completedButton.innerHTML="success";
completedButton.classList.add("complete-btn");
toDoDiv.appendChild(completedButton);
//check delete button
const trashButton = document.createElement('button');
trashButton.innerHTML="delete";
trashButton.classList.add("complete-btn");
toDoDiv.appendChild(trashButton);
//append todo
toDoContainer.appendChild(tododiv);
inputField.value= "";
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>to do list </title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<div class="container">
<header>
<h1>This is your to do list </h1>
<div class="input">
<input type="text" placeholder="what to do ...?" id="text">
<input type="button" value="add" id="addButton">
</div>
</header>
<div id="ToDoContainer">
</div>
</div>
<script src="./script.js"></script>
</body>
</html>
here is a screenshot
sonEtLumiere is right, you have a typo. It should be:
toDoContainer.appendChild(toDoDiv);
Your variable is called toDoDiv, you have an error in this line (penultimate line):
toDoContainer.appendChild(tododiv);
This will work:
toDoContainer.appendChild(toDoDiv);

Categories

Resources