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

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.

Related

Input Value showing as undefined

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.

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>

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);

how do i connect event listener to textarea element?

I really struggling with this.
I need to basically make it so whatever is written in a newly created textbox is stored in local storage.
// TODO: Q1(c)(iii)
// Make an event listener to save text when it changes:
// ...get the textarea element's current value
// ...make a text item using the value
// ...store the item in local storage using the given key
// Connect the event listener to the textarea element
var item, data, key;
var textareaElement = document.createElement("TEXTAREA");
textareaElement.addEventListener("change", function(event) {
var myText = document.getElementById("textareaElement").value;
localStorage.setItem("text", myText);
item = makeItem ("text", myText);
});
-- HTML --
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>My Erehwon Diary ds22368</title>
<meta name="author" content="Stephen Rice" />
<!-- Set viewport to ensure this page scales correctly on mobile devices -->
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="tma03.css" />
<!-- Set demo data -->
<script src="tma03-demo.js"></script>
<!-- Start TMA03 application -->
<script src="tma03.js"></script>
</head>
<body>
<h1>My Erehwon Diary ds22368</h1>
<main>
<section id="text" class="button">
<button type="button">Add entry</button>
</section>
<section id="image" class="button">
<button type="button">Add photo</button>
<input type="file" accept="image/*" />
</section>
</main>
</body>
</html>
The questions for each line are the comments above, and below them is what I've tried so far.
var item, data, key;
var textareaElement = document.createElement("TEXTAREA");
document.body.appendChild(textareaElement); //Add the element to the document
textareaElement.addEventListener("change", function(event) {
var mytext = textareaElement.value; //You already have the element as a variable
localStorage.setItem("text", myText);
item = makeItem("text", myText);
});
function makeItem() { //Don't forget to define makeItem
//code
}
Create an input like this in your HTML
<textarea id=‘textarea’ onchange=‘save()’ />
In JS:
const textarea = document.querySelector(‘#textarea’)
function save() {
localStorage.setItem("text", textarea.value);
}

Using checkboxes to render selected items to <div>

I have a populated table of JSON data with a checkbox next to each---I want it so that when a checkbox is selected it pushes that selected item into an array (in this case the div myFave.hs-gc-header).
When I console.log(arr) it just shows a bunch of empty arrays (I believe one for each of the list items). Not sure why this is--if anyone could shed light on this that would be great.
I think the problem lies with the populateArr() block, but I can't say for sure.
JS:
loadTableData() {
let tableRes = redactedName.d.results.filter(function(val) {
return (val.FileLeafRef.trim().length > 0);
}).map(function(obj) {
return {
// "FileName": obj.FileLeafRef,
// "Path": obj.EncodedAbsUrl,
"Titles": obj.File.Name
}
});
let allTitles = tableRes;
for (var i = 0; i < allTitles.length; i++) {
let tr = $("<tr/>");
$(tr).append("<td> </td>");
$(tr).append("<td>" + allTitles[i].Titles + "</td>");
$(tr).append("<input type='checkbox'/>").addClass("checkbox").val("val");
/* ---------- */
function populateArr() {
let arr = [];
$(".checkbox input[type='checkbox']:checked").each(function() {
arr.push($(this).val());
});
return arr;
}
$("#myFave.hs-gc-header").click(function() {
populateArr();
})
};
HTML snippet
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width,initial-scale=1, shrink-to-fit=no">
<meta name="description" content="description here">
<meta name="keywords" content="keywords,here">
<!------------------------------->
<script
src="https://cdnjs.cloudflare.com/ajax/libs/core-js/2.6.2/core.min.js"></script>
<script
type="text/javascript"
src="dist/js/jquery_wrapper.min.js"></script>
</head>
<body>
<script src="./bundle.js"></script>
<div class="km-div-container">
<div class="col-md-2"> <!-- Left -->
<div class="form-group">
<input
type="search"
class="form-control"
id="searchbar"
placeholder="Search All Documents...">
</div>
<div id="myFave.hs-gc-header">
<p>My Favorites:</p>
</div>
</div>
</div> <!-- km -->
</body>
</html>
I don't think this will work, I had a similar problem while using vanilla JavaScript.
When you append to the dom like below, you won't be able to add event listeners to the html tags.
$(tr).append("<input type='checkbox'/>").addClass("checkbox").val("val");
You should do this in your for loop when you filter for the .checkbox with attribute check it should work.
// convert code to jquery
let checkbox = document.createElement('checkbox');
check.setAttribute('type', 'checkbox');
checkbox.className = 'checkbox';
tr.appendChild(checkbox);

Categories

Resources