input field won't clear up - javascript

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

Related

sending commands/values between pages

im working on a website with 2 pages 1 is the receiver and 2 is the remote basicly you can enter a text on page 2 and once you hit submit page1 starts playing a text to speatch message with the text inut from page2
index.html (aka : page1)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="src/style.css">
</head>
<body>
<h1 id="header"></h1>
<script src="src/script.js"></script>
</body>
</html>
control.html (aka : page2)
<body>
<center>
<form>
<h1 style="color:green">Javatpoint</h1>
<h3> Confirm password Validation Example </h3>
<!-- Enter Password -->
<td> Enter Password </td>
<input type = "password" name = "pswd1"> <br><br>
<button type = "submit" onclick="matchPassword()">Submit</button>
<script>
var pw1 = document.getElementById("pswd1");
function matchPassword() {
<script src="script.js"><script> var x1
}
</script>
script.js of page1
const message = 'Hello world' // Try edit me
// Update header text
document.querySelector('#header').innerHTML = message
// Log to console
console.log(message)
var audio = new Audio('notif.mp3');
audio.play();
var msg = new SpeechSynthesisUtterance();
msg.text = "hallo jeremy";
window.speechSynthesis.speak(msg);
i cant find a way to send the text inside page2 to page 1
There are many ways that you could achieve this, but I'll show you just one. You can easily pass data between pages using query parameters, which are essentially pieces of data appended to the end of a URL.
In order to utilize these, you would need to redirect to your index.html page whenever the user presses the button in the control.html page. Fortunately, this can be done by adding an event listener to your Submit button.
Here is the code below:
control.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" />
</head>
<body>
<form>
<p>Enter stuff here:</p>
<input type="text" id="text-input" name="text" />
<input type="submit" id="submit-button"></input>
</form>
<!-- continue document... -->
<script src="src/control.js"></script>
</body>
</html>
src/script.js
const queryString = window.location.search;
const queryParams = new URLSearchParams(queryString);
const message = queryParams.get("text");
console.log(message);
// continue file...
src/control.js
const button = document.getElementById("submit-button");
button.addEventListener("click", handleText);
function handleText(event) {
event.preventDefault();
const text = document.getElementById("text-input").value;
const currentURL = window.location.pathname;
const currentDir = currentURL.substring(0, currentURL.lastIndexOf("/"));
window.location.replace(currentDir + "/index.html?text=" + text);
}
Hope this helps!

Uncaught TyperError: Cannot read properties of null (reading 'value') at HTMLFormElement.addItem (app.js:21:25) [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last month.
Improve this question
I was trying to create a crud app(local storage) from a Udemy course and ran into the following error in the code, the event Listener is to get the value in the input section once user hits submit;
following is the app.js
`
// ****** SELECT ITEMS **********
const alert = document.querySelector(".alert");
const form = document.querySelector(".grocery-form");
const grocery = document.getElementById(".grocery");
const submitBtn = document.querySelector(".submit-btn");
const container = document.querySelector(".grocery-container");
const list = document.querySelector(".grocery-list");
const clearBtn = document.querySelector(".clear-btn");
// edit option
let editElement;
let editFlag = false;
let edtiID = "";
// ****** EVENT LISTENERS **********
form.addEventListener("submit", addItem);
// ****** FUNCTIONS **********
function addItem(e) {
e.preventDefault();
const value = grocery.value;
const id = new Date().getTime().toString();
console.log(id);
}
`
following is the index.html
`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Grocery Bud</title>
<!-- font-awesome -->
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css"
/>
<!-- styles -->
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<section class="section-center">
<!-- form -->
<form class="grocery-form">
<p class="alert"></p>
<h3>grocery bud</h3>
<div class="form-control">
<input type="text" id="grocery" placeholder="e.g. eggs" />
<button type="submit" class="submit-btn">submit</button>
</div>
</form>
<!-- list -->
<div class="grocery-container">
<div class="grocery-list"></div>
<button class="clear-btn">clear items</button>
</div>
</section>
<!-- javascript -->
<script src="app.js"></script>
</body>
</html>
`
I tried to listen to the submit event and capture the value in the input box in the form. But I got the error value is null, also tried to console log the 'grocery' element, got null instead
grocery is an ID not class, so document.getElementById needs a plain ID just like grocery not .grocery, this would be called class. Just read about Document.getElementById().
// ****** SELECT ITEMS **********
const alert = document.querySelector(".alert");
const form = document.querySelector(".grocery-form");
const grocery = document.getElementById("grocery");
const submitBtn = document.querySelector(".submit-btn");
const container = document.querySelector(".grocery-container");
const list = document.querySelector(".grocery-list");
const clearBtn = document.querySelector(".clear-btn");
// edit option
let editElement;
let editFlag = false;
let edtiID = "";
// ****** EVENT LISTENERS **********
form.addEventListener("submit", addItem);
// ****** FUNCTIONS **********
function addItem(e) {
e.preventDefault();
const value = grocery.value;
const id = new Date().getTime().toString();
console.log(id);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Grocery Bud</title>
<!-- font-awesome -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css" />
<!-- styles -->
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<section class="section-center">
<!-- form -->
<form class="grocery-form">
<p class="alert"></p>
<h3>grocery bud</h3>
<div class="form-control">
<input type="text" id="grocery" placeholder="e.g. eggs" />
<button type="submit" class="submit-btn">submit</button>
</div>
</form>
<!-- list -->
<div class="grocery-container">
<div class="grocery-list"></div>
<button class="clear-btn">clear items</button>
</div>
</section>
</body>
</html>
Or as #Andy mentioned in comments, you can use Document.querySelector().

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.

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.

LocalStorage removes the wrong value

I keep having the same issue again and again : When I add a task, it gets added to the localStorage correctly. But once I have multiple tasks and I click complete on a random one, sometimes it happens that the LocalStorage removes the task before it or after it. I can't figure out a way how to let it work.
let addBtn = document.getElementById("addButton");
let textInput = document.getElementById("textInput");
let mainList = document.getElementById("mainList");
let storage = JSON.parse(localStorage.getItem("toDos")) || [];
if (storage.length != 0){
for (let i=0; i<storage.length;i++){
addTask(mainList, storage[i]);
};
};
function addTask(list,task){
var newTask = document.createElement("li");
newTask.textContent=task
newTask.className="task d-flex justify-content-between list-group-item bg-primary mt-2";
addCompleteBtn(newTask);
list.appendChild(newTask);
}
function addCompleteBtn (newTask){
let completeBtn = document.createElement("button");
completeBtn.className="btn btn-success completeBtn";
completeBtn.textContent="Completed";
newTask.appendChild(completeBtn);
};
addBtn.addEventListener("click", ()=>{
if(textInput.value === ""){
alert("Error: The field is either empty or you entered more than 100 characters!");
}else{
storage.push(textInput.value);
addTask(mainList, textInput.value);
textInput.value="";
localStorage.setItem("toDos",JSON.stringify(storage));
};
});
mainList.addEventListener("click",(evt)=>{
if (evt.target.className==="btn btn-success completeBtn") {
let listItem = evt.target.parentNode;
let mainUl = listItem.parentNode;
let toBeRemoved = listItem.textContent;
storage.splice(storage.indexOf(toBeRemoved),1);
mainUl.removeChild(listItem);
localStorage.setItem("toDos",JSON.stringify(storage));
};
});
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
<title>To-do-list App</title>
</head>
<body>
<div class="jumbotron bg-info">
<div class="container">
<h1 class="display-4 text-center">Task List</h1>
<p class="lead text-center">Click on the Add button to add a task</p>
</div>
</div>
<div class="container">
<div class="firstInput input-group mb-5">
<div class="input-group-prepend">
<button class="btn btn-primary" type="button" id="addButton">Add Task</button>
</div>
<input type="text" title='Enter a Task' class="form-control" id="textInput" maxlength="200">
</div>
</div>
<ul class='tasksList container' id="mainList">
</ul>
<script src="script.js"></script>
</body>
</html>
Shows all the values in the LocalStorage
Once task 2 is removed, task 3 is removed from the Storage instead
this is the specific part that causes me issues :
mainList.addEventListener("click",(evt)=>{
if (evt.target.className==="btn btn-success completeBtn") {
let listItem = evt.target.parentNode;
let mainUl = listItem.parentNode;
let toBeRemoved = listItem.textContent;
/* This is the part of code causing me issues
storage.splice(storage.indexOf(toBeRemoved),1);
*/
mainUl.removeChild(listItem);
localStorage.setItem("toDos",JSON.stringify(storage));
};
});
The problem is here let toBeRemoved = listItem.textContent;,this will return the text content of all elements inside that li. So if you add a task named 'Task 1', when you press Completed the value of toBeRemoved will be Task 1Completed since this will return the text of the button as well since your button is a child of the li.
So change let toBeRemoved = listItem.textContent; to let toBeRemoved = listItem.childNodes[0].nodeValue; and you should be fine, this will get the text of the li only.

Categories

Resources