'Li' element showing as `undefined` - javascript

Started to do a todo list on my own to practice JS
When I add the text/task to the todo, HTML text showing-
Undefined
Made sure getElementbyId etc was right but unsure if missing something. Design is rubbish, just want to try JS out.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link type="text/css" rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<title>To doist</title>
</head>
<body>
<div class= "main-title-bar">
<h1>To doist</h1>
</div>
<div id = "button">
<button>+</button>
</div>
<div class = "input" id = "input">
<input type="text" class="add_tast" placeholder="Task">
<span onclick="newElement()" onkeypress="newElement()" class="addBtn">Add</span>
</div>
<div class = "todo-list">
<ul id="myUL">
</ul>
</div>
<script src="js/app.js"></script>
</body>
</html>
JAVASCRIPT
//Click button to get input field
let button = document.getElementById('button')
button.addEventListener("click",showInput)
function showInput(event){
if(event.type === "click"){
input.classList.toggle("show")
}
}
const input = document.querySelector(".input")
// Create new element for the classList
function newElement(){
let li = document.createElement("li");
let inputValue = document.getElementById("input").value;
let t = document.createTextNode(inputValue);
li.appendChild(t);
if (inputValue === ''){
alert("You must write something!");
} else {
document.getElementById("myUL").appendChild(li);
}
document.getElementById("input").value = "";
console.log('Is it working?');
}
Expecting to see the name of my task on HTML as for example "Going to the gym"

You have given the id="input" to the div instead of the input element. Give the id to the input an it will work
let button = document.getElementById('button')
button.addEventListener("click",showInput)
function showInput(event){
if(event.type === "click"){
input.classList.toggle("show")
}
}
const input = document.querySelector(".input")
function newElement(){
let li = document.createElement("li");
let inputValue = document.getElementById("input").value;
let t = document.createTextNode(inputValue);
li.appendChild(t);
if (inputValue === ''){
alert("You must write something!");
} else {
document.getElementById("myUL").appendChild(li);
}
document.getElementById("input").value = "";
console.log('Is it working?');
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link type="text/css" rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<title>To doist</title>
</head>
<body>
<div class= "main-title-bar">
<h1>To doist</h1>
</div>
<div id = "button">
<button>+</button>
</div>
<div class = "input" >
<input type="text" id = "input" class="add_tast" placeholder="Task">
<span onclick="newElement()" onkeypress="newElement()" class="addBtn">Add</span>
</div>
<div class = "todo-list">
<ul id="myUL">
</ul>
</div>
<script src="js/app.js"></script>
</body>
</html>

I have fixed your code. document.getElementById("input").value;
input tag is not id it's tag.
if you want get value from input tag must using through id use to this code.
document.getElementById("id").value;
let button = document.getElementById('button')
button.addEventListener("click",showInput)
function showInput(event){
if(event.type === "click"){
input.classList.toggle("show")
}
}
const input = document.querySelector(".input")
// Create new element for the ClassList
function newElement(){
debugger;
let li = document.createElement("li");
let inputValue = $("#tasks").val();
let t = document.createTextNode(inputValue);
li.appendChild(t);
if (inputValue === ""){
alert("You must write something!");
} else {
document.getElementById("myUL").appendChild(li);
}
document.getElementById("input").value = "";
console.log('Is it working?');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link type="text/css" rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<title>To doist</title>
</head>
<body>
<div class= "main-title-bar">
<h1>To doist</h1>
</div>
<div id = "button">
<button>+</button>
</div>
<div class = "input" id = "input">
<input type="text" id="tasks" class="add_tast" placeholder="Task">
<span onclick="newElement()" onkeypress="newElement()" class="addBtn">Add</span>
</div>
<div class = "todo-list">
<ul id="myUL">
</ul>
</div>
<script src="js/app.js"></script>
</body>
</html>

Related

I am unable to add event listener to li which is created by JS

I am unable to adding event listener to list item which is created by JavaScript.
I am trying to add a event listener to list item such that if I double click to any list item it will remove that particular list item from the DOM.
// Declaring Variables
let inputbtn = document.getElementById('input-but');
let addBtn = document.getElementById('add-button');
let list = document.getElementById('text');
addBtn.addEventListener('click', getVal)
// Adding Function to Add New task
function getVal() {
let value = inputbtn.value;
if (value === "") {
alert("Please fill out this field.")
}
else {
let newElement = document.createElement('li')
let liText = document.createTextNode(value)
newElement.appendChild(liText)
list.appendChild(newElement)
}
document.myForm.reset()
}
// Removing Task by ___________
<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 List Trial</title>
<link rel="stylesheet" href="Trial.css">
</head>
<body>
<h3>To do list</h3>
<form action="" name="myForm">
<input type="text" id="input-but" required>
<input type="button" id="add-button" value="Add Task">
<ul id="text"></ul>
</form>
<!-- JavaScript Source -->
<script src="Trial.js"></script>
</body>
</html>
Instead of adding listeners to each list item add one to the ul element and use event delegation to catch dblclick events as they bubble up the DOM.
let inputbtn = document.getElementById('input-but');
let addBtn = document.getElementById('add-button');
let list = document.getElementById('text');
addBtn.addEventListener('click', getVal)
list.addEventListener('dblclick', handleClick, false);
function handleClick(e) {
if (e.target.nodeName === 'LI') {
e.target.remove();
}
}
function getVal() {
let value = inputbtn.value;
if (value === "") {
alert("Please fill out this field.")
} else {
let newElement = document.createElement('li')
let liText = document.createTextNode(value)
newElement.appendChild(liText)
list.appendChild(newElement)
}
}
<h3>To do list</h3>
<input type="text" id="input-but" required>
<input type="button" id="add-button" value="Add Task">
<ul id="text"></ul>
In this scenario event delegation can come to the rescue. Create one listener function and let that function determine if an action should be performed. Add the listener on the document level for the event types you want the listener to handle.
Here's a snippet to play with.
See also
document.addEventListener(`click`, handle);
document.addEventListener(`dblclick`, handle);
function handle(evt) {
if (evt.target.id === `add-button`) {
const inp = document.querySelector(`#input-but`);
const value = inp.value.trim();
if (value) {
inp.removeAttribute(`placeholder`);
document.querySelector(`ul#text`)
.insertAdjacentHTML(`beforeend`,
`<li class="point">${value}</li>`);
return inp.value = ``;
}
inp.value = ``;
return inp.setAttribute(`placeholder`, `Hey, give me some text!`)
}
if (evt.type === `dblclick` && evt.target.closest(`li`)) {
evt.preventDefault();
evt.target.closest(`li`).remove();
}
}
.point {
cursor: pointer;
}
.point:hover::after {
content: ' (double click to remove)';
color: red;
}
<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 List Trial</title>
<link rel="stylesheet" href="Trial.css">
</head>
<body>
<h3>To do list</h3>
<form action="" name="myForm">
<input type="text" id="input-but" required>
<input type="button" id="add-button" value="Add Task">
<ul id="text"></ul>
</form>
<!-- JavaScript Source -->
<script src="Trial.js"></script>
</body>
</html>
You can add a listener to the newElement before appending to the parent.
newElement.addEventListener('dblclick', () => newElement.remove());
// Declaring Variables
let inputbtn = document.getElementById('input-but');
let addBtn = document.getElementById('add-button');
let list = document.getElementById('text');
addBtn.addEventListener('click', getVal)
// Adding Function to Add New task
function getVal() {
let value = inputbtn.value;
if (value === "") {
alert("Please fill out this field.")
}
else {
let newElement = document.createElement('li')
let liText = document.createTextNode(value)
newElement.appendChild(liText)
// Removing Task by ___________
newElement.addEventListener('dblclick', () => newElement.remove());
list.appendChild(newElement)
}
document.myForm.reset()
}
<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 List Trial</title>
<link rel="stylesheet" href="Trial.css">
</head>
<body>
<h3>To do list</h3>
<form action="" name="myForm">
<input type="text" id="input-but" required>
<input type="button" id="add-button" value="Add Task">
<ul id="text"></ul>
</form>
<!-- JavaScript Source -->
<script src="Trial.js"></script>
</body>
</html>
But a simpler solution might be to use event delegation and add a single listener to the parent ul.
list.addEventListener('dblclick', (e) => {
if (e.target.closest('li')) {
e.target.closest('li').remove();
}
})
// Declaring Variables
let inputbtn = document.getElementById('input-but');
let addBtn = document.getElementById('add-button');
let list = document.getElementById('text');
addBtn.addEventListener('click', getVal)
// Adding Function to Add New task
function getVal() {
let value = inputbtn.value;
if (value === "") {
alert("Please fill out this field.")
}
else {
let newElement = document.createElement('li')
let liText = document.createTextNode(value)
newElement.appendChild(liText)
list.appendChild(newElement)
}
document.myForm.reset()
}
// Removing Task by ___________
list.addEventListener('dblclick', (e) => {
if (e.target.closest('li')) {
e.target.closest('li').remove();
}
})
<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 List Trial</title>
<link rel="stylesheet" href="Trial.css">
</head>
<body>
<h3>To do list</h3>
<form action="" name="myForm">
<input type="text" id="input-but" required>
<input type="button" id="add-button" value="Add Task">
<ul id="text"></ul>
</form>
<!-- JavaScript Source -->
<script src="Trial.js"></script>
</body>
</html>
just add event listener to the created list item.
newElement.addEventListener("dblclick", function() {
newElement.remove();
});
it works! 👍
Here it is line 19 newElement.ondblclick=(e)=>newElement.remove()
// Declaring Variables
let inputbtn = document.getElementById('input-but');
let addBtn = document.getElementById('add-button');
let list = document.getElementById('text');
addBtn.addEventListener('click', getVal)
// Adding Function to Add New task
function getVal() {
let value = inputbtn.value;
if (value === "") {
alert("Please fill out this field.")
}
else {
let newElement = document.createElement('li')
let liText = document.createTextNode(value)
newElement.appendChild(liText)
list.appendChild(newElement)
newElement.ondblclick=(e)=>newElement.remove()
}
document.myForm.reset()
}
// Removing Task by ___________
<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 List Trial</title>
<link rel="stylesheet" href="Trial.css">
</head>
<body>
<h3>To do list</h3>
<form action="" name="myForm">
<input type="text" id="input-but" required>
<input type="button" id="add-button" value="Add Task">
<ul id="text"></ul>
</form>
<!-- JavaScript Source -->
<script src="Trial.js"></script>
</body>
</html>

My EDIT button is not working properly? (Javascript Todo List) Beginner

I am a beginner in Javascript and is currently trying to make a todo list web app. But currently stucked at the edit button.
As you can see, I wanted to make an editable checklist but somehow everytime I hit the edit button, a new input comes out instead of replacing the current one. It also removes the 'checkbox' somehow.
Can anyone tell me where I did wrong? Thank you for your time!
Somehow the edit button doesn't work at all when I try to run it on VSCode. Here it works, but not as I wanted though.
const ul = document.querySelector('#invitedList');
ul.addEventListener('click', (event) => {
if(event.target.tagName === 'BUTTON') {
const button = event.target;
const li = button.parentNode;
if(button.textContent === 'edit') {
const span = li.firstElementChild;
const input = document.createElement('input');
input.type = 'text';
input.value = span.textContent;
li.insertBefore(input, span);
li.removeChild(span);
button.textContent = 'save';
} else if(button.textContent === 'save') {
const input = li.firstElementChild;
const span = document.createElement('span');
span.textContent = input.value;
li.insertBefore(span, input);
li.removeChild(input);
button.textContent = 'edit';
}
}
});
<!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>
<script src="test.js"></script>
</head>
<body>
<!-- TASK LIST THAT IS SUPPOSED TO BE EDITABLE GOES DOWN HERE, AS A TEMPLATE -->
<div id="taskit" class="task">
<ul id="invitedList">
<input type="checkbox"/>
<label>
<span id="editable" class="custom-checkbox">Edit This</span>
</label>
<button type="submit" id="editbtn">edit</button>
</ul>
</div>
</body>
</html>
Have you considered trying Node.ReplaceChild() instead of creating a new element? Not sure how to tell you exactly how to do it but here is a link to the documentation:
https://developer.mozilla.org/en-US/docs/Web/API/Node/replaceChild
I'd suggest to change styling instead of creating and removing elements. Here is possible solution:
let isEditState = false;
const editButton = document.querySelector('#editbtn');
editButton.addEventListener('click', (event) => {
const span = document.querySelector('#editable');
const checkbox = document.querySelector('#checkbox');
const text = document.querySelector('#text');
if (isEditState) {
span.innerText = text.value;
checkbox.style.display = 'inline';
text.style.display = 'none';
editButton.innerText = 'edit';
} else {
checkbox.style.display = 'none';
text.style.display = 'inline';
editButton.innerText = 'save';
}
isEditState = !isEditState;
});
<!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 id="taskit" class="task">
<ul id="invitedList">
<input type="checkbox" id="checkbox"/>
<input type="text" id="text" style="display: none"/>
<label>
<span id="editable" class="custom-checkbox">Edit This</span>
</label>
<button type="submit" id="editbtn">edit</button>
</ul>
</div>
</body>
</html>

Keep body scrolled at the bottom unless user scrolls up in javascript

I have a program where the user types in something and then something outputs in the "console." The most recent entered thing stays at the bottom unless the user scrolls up
The body of my document seems to be where I can dd effects like hidden scroll to it. I read another post and used scrollTop and scrollHeight and it is not working.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href = "style.css">
</head>
<body id = "scroll">
<div id="game">
<div id="console">
</div>
</div>
<div id = "command-box">
<div id = "cmd">
<input id = "command" onkeypress = "doAThing(event);">
</div>
</div>
</div>
<script src = "variables.js"></script>
<script src = "code.js"></script>
</body>
</html>
var input = document.querySelector("#command");
var theConsole = document.querySelector("#console");
theConsole.scollTop = theConsole.scrollHeight;
var myScroll = document.getElementById("scroll");
function doAThing(event) {
var theKeyCode = event.keyCode;
if(theKeyCode === 13) acceptCommand();
setInterval(scrollUpdate, 1000);
}
function scrollUpdate() {
myScroll.scrollTop = myScroll.scrollHeight;
}
function acceptCommand() {
var p = document.createElement("p");
if(input.value === "hi") theConsole.append("Hi!", p);
if(input.value === "ping") theConsole.append("Pong!", p);
}

Count key presses and display them in HTML

I made a simple "spacebar simulator" game with HTML and JavaScript. Every time the user presses spacebar an image is replaced with another one, and when the key is released it is reset to the original image.
I would like to add a counter to the page, which counts the number of times the user has pressed spacebar. The source code is below:
var myRealUrl = "./assets/spacebar.png";
$("body").on("keydown", function (e) {
if(e.which == 32){
$("#spacebar").attr("src", "./assets/spacebar_pressed.png")
}
});
$("body").keyup(function (e) {
$("#spacebar").attr("src", myRealUrl)
});
var button = document.getElementById('counter'),
count = 0;
button.onclick = function() {
count += 1;
button.innerHTML = "Click me: " + count;
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="sv">
<head>
<meta charset="utf-8">
<title></title>
<link href="https://fonts.googleapis.com/css?family=Montserrat:300,400" rel="stylesheet">
<link rel="stylesheet" href="css/stylesheet.css">
<script src="js/jquery-3.2.1.min.js"></script>
</head>
<body>
<div class="container">
<div class="title">
<h1>Spacebar Simulator 2018</h1>
<span id="counter"><p></p></span>
</div>
<img src="assets/spacebar.png" id="spacebar">
<p>Pressed</p><p id="counter">0</p><p> times.</p>
<footer>
<p>© 2018</p>
</footer>
</div>
<script src="js/spacebar.js"></script>
</body>
</html>
So set up a page level variable and increment it in the keydown event handler.
Your attempt at the "button" click code didn't work because the p element that needed to be clicked had no content inside of it, so it wasn't rendering on the screen and therefore there was nothing to click on.
Also, you can't have more than one element with the same id and it's invalid to put a p inside of a span.
var counter = 0; // Variable to hold the count
var myRealUrl = "./assets/spacebar.png";
var count = document.getElementById('counter');
$("body").on("keydown", function (e) {
if(e.which == 32){
counter++; // Increment the counter
$("#spacebar").attr("src", "./assets/spacebar_pressed.png");
count.textContent = counter; // Log the count
}
});
$("body").keyup(function (e) {
$("#spacebar").attr("src", myRealUrl)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="sv">
<head>
<meta charset="utf-8">
<title></title>
<link href="https://fonts.googleapis.com/css?family=Montserrat:300,400" rel="stylesheet">
<link rel="stylesheet" href="css/stylesheet.css">
<script src="js/jquery-3.2.1.min.js"></script>
</head>
<body>
<div class="container">
<div class="title">
<h1>Spacebar Simulator 2018</h1>
</div>
<img src="assets/spacebar.png" id="spacebar">
<p>Pressed <span id="counter">0</span> times.</p>
<footer>
<p>© 2018</p>
</footer>
</div>
<script src="js/spacebar.js"></script>
</body>
</html>

Combining keypress and click

There are posts where this is mentioned but in J Query which i have not learned yet. I have been trying to add the item once the user click on screen or keyboard. When the user clicks on screen it seems to be working perfectly but then when the user presses enter on keyboard, the items shows up for less than a millisecond then disappears. Also, if you can kindly mention how can I add a remove function to remove an item the user click on.
Here is the HTML:
<!DOCTYPE html>
<html>
<head>
<title>Simple Shopping Cart</title>
<link rel="stylesheet" type="text/css" href="index.css">
</head>
<body>
<p class="buy">Buy your items anywhere and anytime</p>
<p class="click">click on an item to remove it</p>
<form>
<input type="text" class="item" placeholder="Item:">
<button type="button">Add item</button>
</form>
<br>
<ul>
</ul>
<script type="text/javascript" src="index.js"></script>
</body>
</html>
and here is the JavaScript:
const input = document.querySelector(".item");
const btn = document.querySelector("button");
const ul = document.querySelector("ul");
function inputLength() {
return input.value.length;
}
function add() {
var li = document.createElement("li");
li.appendChild(document.createTextNode(input.value));
ul.appendChild(li);
}
function addItem() {
if (inputLength() > 0) {
add();
}
}
function addItemPress(event) {
if (inputLength() > 0 && event.which === 13) {
add();
}
}
btn.addEventListener("click", addItem);
input.addEventListener("keypress", addItemPress)
By default, forms will reset the page when they are submitted, unless you set the action property to "#". To run JavaScript when a form is submitted, you can use the onSubmit property. These approaches can be combined like this:
index.html:
<!DOCTYPE html>
<html>
<head>
<title>Simple Shopping Cart</title>
<link rel="stylesheet" type="text/css" href="index.css">
</head>
<body>
<p class="buy">Buy your items anywhere and anytime</p>
<p class="click">click on an item to remove it</p>
<form id="addItemForm" action="#" onsubmit="add()">
<input type="text" class="item" placeholder="Item:">
<button type="submit">Add item</button>
</form>
<br>
<ul>
</ul>
<script type="text/javascript" src="index.js"></script>
</body>
</html>
index.js:
const input = document.querySelector(".item");
const btn = document.querySelector("button");
const ul = document.querySelector("ul");
const form = document.getElementById("addItemForm");
function add() {
if (input.value.length > 0) {
var li = document.createElement("li");
li.appendChild(document.createTextNode(input.value));
ul.appendChild(li);
form.reset();
}
}

Categories