Combining keypress and click - javascript

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

Related

How to make a to-do list app present the input submitted to it

New coder here. I am trying to create a simple to-do list but clicking on the submit button is not returning any input.
Can you help me fix this? My code is below:
<!DOCTYPE html>
<html lang="en">
<head>
<title>To-Do List</title>
<meta charset=""utf-8>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
<style>
#interface {
background-color: rgb(220, 216, 216);
}
</style>
</head>
<body class="container" id="interface">
<h1>To-Do List</h1>
<h2>By Thabo Mtetwa</h2>
<h4 id= "description">From office tasks, to household chores, and personal memos - this to-do list is a great way to keep track of them all.</h4>
<div class="container">
<h3>Item</h3>
<input type="text" id="item-input" placeholder="Add item here">
<br><br>
<div button type="button" class="btn btn-primary" id="submit">Submit</button>
</div>
<div id="todo-container">
</div>
</div>
<script>
let inputField = document.getElementById("item-input");
let addButton = document.getElementById("submit");
let listArea = document.getElementById("todo-container");
addButton.addEventListener("click", function() {
var listItems = document.createElement("li");
ListItems.innerText = listArea.value;
listArea.appendChild(ListItems);
});
</script>
</body>
</html>
I created a variable to capture the information submitted in the input field, and set it to present this information in the list area below the input field. But this has not worked.
You have an error in casing for the listItems variable. You should change it everywhere to start from the lowercase letter.
Also, you should use inputField.value for TODO item values.
Below there is an improved event handler
addButton.addEventListener("click", function() {
var listItems = document.createElement("li");
listItems.innerText = inputField.value;
listArea.appendChild(listItems);
});
See jsfiddle for an example of the working code.

Value from Input box not showing

So I am trying to create a simple to-do application. The list itself works perfectly fine and things get added how they should.
However, now I am trying to have a sort of timeline that basically shows the todo items in a different style.
Now the issue is every time an item gets added, it shows up in the regular checklist but not in the new timeline. The LI gets created but with no content inside of it.
Any of you guys know how I can display the input value from the input box into the timeline as I did with the regular checklist?
let inputValue = document.getElementById("inputValue");
let addButton = document.getElementById("addButton");
let frm = document.querySelector("form");
//Prevent Refresh
function handleForm(event) {
event.preventDefault();
}
function addItem() {
// Check Input for empty value
if (inputValue.value.length == 0) {
alert("Your Input was empty");
return;
}
//Create LI and append to UL
let listItem = document.createElement("li");
listItem.innerText = inputValue.value;
let ul = document.getElementById("list-ul")
ul.appendChild(listItem);
listItem.className = "list-item";
//Create Delet button and append to LI
let deleteButton = document.createElement("button");
listItem.appendChild(deleteButton);
deleteButton.className = "delete-button";
deleteButton.innerHTML = '<i class="far fa-trash-alt"></i>';
deleteButton.addEventListener("click", deleteItem);
//Reset the Input
frm.reset();
//Prevent refresh
frm.addEventListener('submit', handleForm);
//Delete Function
function deleteItem(e) {
console.log("Item deleted");
listItem.remove();
}
//Timeline
let timeline = document.getElementsByClassName("timeline");
let timeUl = document.getElementById("time-ul");
//Create LI for timeline
let timelineItem = document.createElement("li");
timelineItem.innerText = inputValue.value;
timeUl.appendChild(timelineItem);
}
<!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="style.css">
<script src="https://kit.fontawesome.com/e7a951e13e.js" crossorigin="anonymous"></script>
<link href="https://fonts.googleapis.com/css2?family=Montserrat:wght#100;200;300;400;500;600;700;800&display=swap" rel="stylesheet">
<title>Document</title>
</head>
<body>
<main>
<div class="container">
<h1>To Do</h1>
<form>
<input type="text" id="inputValue">
<button type="button" id="addButton" onclick="addItem();">Add Item</button>
<!-- <button type="button" id="clearAll" onclick="clearAll();">Clear All</button> -->
</form>
<div id="list-container">
<ul id="list-ul">
</ul>
</div>
<div class="timeline">
<ul id="time-ul">
</ul>
</div>
</div>
</main>
<script src="index.js"></script>
</body>
</html>
You are reseting the form and later trying to access the value from the input, which was cleared.
Move frm.reset(); to after the Timeline is updated.
...
//Timeline
let timeline = document.getElementsByClassName("timeline");
let timeUl = document.getElementById("time-ul");
//Create LI for timeline
let timelineItem = document.createElement("li");
timelineItem.innerText = inputValue.value;
timeUl.appendChild(timelineItem);
//Reset the Input
frm.reset();
Another option you have is to store the input value in a variable and use it in your calls before resetting the form.
const todoValue = inputValue.value;
...
//Timeline
timelineItem.innerText = todoValue;
Alright, i was just blind and forgot that i cleared the input by resetting the form.

adding check boxes to my unordered list with javascript

I am doing a project where i need to make a todo list and then when a user clicks the add button itll pull the info in and create a new li item and it to my ul list. But i need my li's to be created with a checkbox attribute attached to them as well and i am stuck, My code is below
// this creates a new li based on the entered value in the text box that it gets when you hit the button
function addItem() {
let newLi = document.createElement("li");
let myLiValue = document.getElementById('textBoxAdd').value;
let liTextNode = document.createTextNode(myLiValue);
newLi.appendChild(liTextNode);
// this just makes sure a user cant enter in a blank value
if (myLiValue == "") {
alert("Please Enter Something Before Hitting Add Item");
} else {
document.getElementById('theNewList').appendChild(newLi);
document.getElementById('textBoxAdd').value = "";
}
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>To-Do List</title>
<link rel="stylesheet" href="main.css">
<script src="main.js" async></script>
</head>
<body>
<main>
<h1>Brody's Wonderful List Of Things</h1>
<h3>Enter a Item and Press "Add Item" to Add to Your List</h3>
<section>
<div class="">
<label>Please Enter in Your TODO Item</label>
<input type="text" id="textBoxAdd">
<button type="button" id="addBtn" onclick="addItem()">Add Item</button>
</div>
</section>
<section>
<ul id="theNewList">
</ul>
</section>
</main>
</body>
</html>
To add a checkbox you can use the following:
let newCheckBoxID = 'checkbox_' + myLiValue;
let newCheckBox = document.createElement("INPUT");
newCheckBox.setAttribute("type", "checkbox");
newCheckBox.setAttribute("id", newCheckBoxID);
newLi.appendChild(newCheckBox);
You'll notice I added code to give the checkbox an ID. Chances are that you'll want to use the value of the checkbox in code somewhere so making sure it has ID set would be necessary. For actual use you'll want to massage the myLiValue to not have spaces and whatnot first before you make it part of an id. Also, I would probably add that id to some array somewhere too as the checkboxes are created...
Next, I would consider putting your text in a LABEL tag instead of leaving it as raw text in the LI
let newCheckLabel = document.createElement('LABEL');
newCheckLabel.setAttribute('for', newCheckBoxID);
let labelTextNode = document.createTextNode(myLiValue);
newCheckLabel.appendChild(labelTextNode);
newLi.appendChild(newCheckLabel);
// this creates a new li based on the entered value in the text box that it gets when you hit the button
function addItem() {
let newLi = document.createElement("li");
let myLiValue = document.getElementById('textBoxAdd').value;
let newCheckBoxID = 'checkbox_' + myLiValue;
let newCheckBox = document.createElement("INPUT");
newCheckBox.setAttribute("type", "checkbox");
newCheckBox.setAttribute("id", newCheckBoxID);
newLi.appendChild(newCheckBox);
let newCheckLabel = document.createElement('LABEL');
newCheckLabel.setAttribute('for', newCheckBoxID);
let labelTextNode = document.createTextNode(myLiValue);
newCheckLabel.appendChild(labelTextNode);
newLi.appendChild(newCheckLabel);
// this just makes sure a user cant enter in a blank value
if (myLiValue == "") {
alert("Please Enter Something Before Hitting Add Item");
} else {
document.getElementById('theNewList').appendChild(newLi);
document.getElementById('textBoxAdd').value = "";
}
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>To-Do List</title>
<link rel="stylesheet" href="main.css">
<script src="main.js" async></script>
</head>
<body>
<main>
<h1>Brody's Wonderful List Of Things</h1>
<h3>Enter a Item and Press "Add Item" to Add to Your List</h3>
<section>
<div class="">
<label>Please Enter in Your TODO Item</label>
<input type="text" id="textBoxAdd">
<button type="button" id="addBtn" onclick="addItem()">Add Item</button>
</div>
</section>
<section>
<ul id="theNewList">
</ul>
</section>
</main>
</body>
</html>

'Li' element showing as `undefined`

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>

Showing how many completed tasks VS how many tasks there are in a JS ToDo list

So I've been making a really simple ToDo list using HTML, JS and CSS and the only thing left is to show the user how many tasks there are and how many are completed. E.g. if there is 3 completed ones and 7 tasks in all, it should output 3/7. I've been trying to do this with some eventlisteners and stuff, but can't get it to work... How can I do this using the ouput element in the HTML and JS?
var button = document.getElementById('button')
var ul = document.getElementById('todo')
var output = document.getElementsByName('result')
button.addEventListener("click", addTask);
button.addEventListener("click", function(event) {
event.preventDefault()
})
function addTask() {
var checkbox = document.createElement("INPUT")
checkbox.setAttribute("type", "checkbox");
var label = document.createElement("LABEL");
var li = document.createElement("LI");
var task = document.createTextNode(document.getElementById('task').value);
label.appendChild(task)
li.appendChild(label)
li.insertBefore(checkbox, li.childNodes[0])
ul.appendChild(li)
var date = new Date()
tasks.push({
text: document.getElementById('task').value,
date: date
})
}
var tasks = []
console.log(tasks)
#todo {
list-style-type: none;
margin-left: 0;
padding-left: 0;
}
input[type=checkbox]:checked + label {
text-decoration: line-through;
}
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<meta charset="utf-8">
</head>
<body>
<header>
<h1>To-do list</h1>
</header>
<form class="" action="" method="">
<input type="submit" name="button" value="Add task" id="button">
<input type="text" name="input" id="task" autofocus>
<output name="result"></output>
<ul id="todo"></ul>
</form>
<script type="text/javascript" src="todo.js"></script>
</body>
</html>
This approach adds two elements to show completed todos and the total count. Likewise, binds the event change to every newly created checkbox to capture when the user clicks on them.
var button = document.getElementById('button')
var ul = document.getElementById('todo')
var output = document.getElementsByName('result')
var total = document.getElementById('total')
var completed = document.getElementById('completed')
button.addEventListener("click", addTask);
button.addEventListener("click", function(event) {
event.preventDefault();
});
function addTask() {
var checkbox = document.createElement("INPUT");
checkbox.setAttribute("type", "checkbox");
// Add one more todo in total count.
total.textContent = +total.textContent + 1;
//Thrigger the completed event
checkbox.addEventListener("change", function(event) {
if (this.checked) completed.textContent = +completed.textContent + 1;
else completed.textContent = +completed.textContent - 1;
});
var label = document.createElement("LABEL");
var li = document.createElement("LI");
var task = document.createTextNode(document.getElementById('task').value);
label.appendChild(task)
li.appendChild(label)
li.insertBefore(checkbox, li.childNodes[0])
ul.appendChild(li)
var date = new Date()
tasks.push({
text: document.getElementById('task').value,
date: date
});
}
var tasks = []
console.log(tasks)
#todo {
list-style-type: none;
margin-left: 0;
padding-left: 0;
}
input[type=checkbox]:checked+label {
text-decoration: line-through;
}
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<meta charset="utf-8">
</head>
<body>
<header>
<h1>To-do list</h1>
</header>
<form class="" action="" method="">
<input type="submit" name="button" value="Add task" id="button">
<input type="text" name="input" id="task" autofocus>
<output name="result"></output>
<p>My completed todos: <span id='completed'>0</span> / <span id='total'>0</span> </p>
<ul id="todo"></ul>
</form>
<script type="text/javascript" src="todo.js"></script>
</body>
</html>
The reason why its not working is because you put it inside a form. Forms should be used only when you want to submit a POST or PUT request to the server running the website. When the button of "submit" is pressed the browser refreshes the page because it sent a POST request to the server, and it responded (most likely with a 404 - Not Found). So firstly, you have to remove the form.
Second, I advise you strongly to use jQuery instead of using regular DOM manipulation methods. It is way faster, more scalable and not to mention easier to read and write. Here is a Plunker with your code that I adapted slightly to make it work.You can view it here.
var tasks = []
var button = $('#button')
var ul = $('#todo')
var output = $('#result')
button.click(function() {
addTask();
});
function addTask() {
var li = $('<li/>');
var checkbox = $('<input/>')
.attr('type', 'checkbox');
var taskText = $('#task').val();
var label = $('<label/>')
.html(taskText);
li.append(checkbox);
li.append(label);
ul.append(li);
var now = new Date()
tasks.push({
text: taskText,
date: now
});
console.log(tasks);
}
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<meta charset="utf-8">
</head>
<body>
<header>
<h1>To-do list</h1>
</header>
<div>
<button name="button" value="Add task" id="button">Add task</button>
<input type="text" name="input" id="task" autofocus>
<output name="result"></output>
<ul id="todo"></ul>
</div>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script type="text/javascript" src="todo.js"></script>
</body>
</html>

Categories