Show form input on page using JavaScript - javascript

I’m in a programming course and I need to create a “To-Do” list page using javascript and HTML. Whatever the user types in the text box should show up below a "To-Do List" heading lower on the page. I’m having trouble getting the information submitted in the form to show up on the page below the To Do list heading. Here’s my code so far.
const formE1 = document.getElementById('todo-form');
const inputE1 = document.getElementById('todo-item');
const list = document.getElementById('to-do');
formE1.addEventListener('submit', function(event) {
event.preventDefault();
const li = document.getElementById('the-list');
document.createElement('li');
inputE1.appendChild(li);
console.log(formE1)
})
const input = document.querySelector('ol');
let template = ''
for (let i = 0; i < inputE1.length; i++) {
const item = `
<li>
<p>Name: ${inputE1}</p>
</li>
`
template += item;
}
input.innerHTML = template;
<!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>Forms</title>
</head>
<body>
<h1>Add a Todo</h1>
<div id="todo-list">
<form id="todo-form">
<input type="text" id="todo-item" placeholder="List Item"/>
<input type="submit" id="todo-add" value="Submit"/>
</form>
<div id="to-do">
<h2>To-Do List</h2>
<ol id="the-list"></ol>
</div>
</div>
<script src="main.js"></script>
</body>
</html>

The key thing is that you were trying to execute code outside of the handler.
You can simplify your code a little. There's no real need for a form element, for example, so add the listener to your button.
const button = document.querySelector('button');
const input = document.querySelector('input');
const list = document.querySelector('ol');
button.addEventListener('click', function(e) {
const li = document.createElement('li');
li.textContent = input.value;
list.appendChild(li);
});
<h1>Add a Todo</h1>
<div>
<input type="text" placeholder="List Item" />
<button type="button">Submit</button>
<div>
<h2>To-Do List</h2>
<ol></ol>
</div>
</div>

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.

How do i add edit buttons next to contacts in my contact list?

I specifically got an account on here to ask about this code where I've been sitting for a good while without finding a solution.
I'm new with coding and I am making a contacts list in Javascript where I so far have managed to make the list, but now I want to add buttons on the side of each contact, one where I can edit the contact and another where I can delete it. But I can't manage to create a button input through my js code.
Specifically for how I want the edit button to work is to change the attribute of the contacts name/number from readonly to where you can write and change it. Also, if there are any other improvements I could make to the rest of my code please let me know!
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">
<title>contacs list</title>
</head>
<h1>Your contacts</h1>
<hr>
<section>
<form id="getForm">
<label>Name:</label>
<input
placeholder = " Bertil..."
type="text"
id="contactName">
<label>phone:</label>
<input
placeholder = "xxx-xxx-xx-xx"
type="text"
id="contactNumber">
<input
type="submit"
class="saveButton"
onclick="getContact()">
</form>
</section>
<section>
<h3>My contacts</h3>
<div>
<ul id="contactsList">
</ul>
</div>
</section>
Javascript:
var contactList = [];
var getContact = function(){
event.preventDefault();
var newContact = {
name: document.getElementById("contactName").value,
number: document.getElementById("contactNumber").value
}
contactList.push(newContact);
console.log(contactList)
printList();
}
var printList = function (){
var li = document.createElement("li");
li.innerText = " ";
var list = document.getElementById("contactsList");
for (var i = 0; i < contactList.length; i++) {
li.innerText = contactList[i].name + " " + contactList[i].number + " ";
list.appendChild(li);
}
}
Thanks!
I have tried a bunch of things but none work so I think they're irrelevant?

Hard stuck for 3 days in a simple to do list

after months of doing courses, I finally ventured into coding my first project, but the most basic functionality of it isn't working.
I'm doing a simple to do list, and im working on it actually displaying the elements added by the user through the button but they don't appear on the screen after clicking, even if i'm using DOM manipulation commands to create an 'ul' element. Also, the page refreshes after every click on the button.
let addToButton = document.getElementById('addButton');
let inputFieldset = document.getElementById('toDoInput');
let toDoContainer = document.getElementById('toDoList');
addToButton.addEventListener('click', function(){
let toDoStuff = document.createElement('ul')
toDoStuff = inputFieldset.value
toDoContainer.append(toDoStuff);
})
<!DOCTYPE html>
<html lang="en">
<head>
<title>la lista</title>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link rel="stylesheet" href="list-style.css"/>
</head>
<body>
<main>
<h1>Ysmael's To-Do List</h1>
<h3>Input your activities</h3>
<form>
Input something<input type="text" required id="toDoInput" placeholder="Input your stuff"/><button id="addButton" type="submit">+</button>
</form>
<div id="toDoList">
</div>
</main>
<script href="todolist.js"></script>
</body>
</html>
Acording to my logic, it should work, but I'm clearly doing one or more things wrong.
to not submit the form, replace the <button> with <input type="button" value="+"> and to create list you want <li> element with the parent <ul>
let addToButton = document.getElementById('addButton');
let inputFieldset = document.getElementById('toDoInput');
let toDoContainer = document.getElementById('toDoList');
addToButton.addEventListener('click', function() {
// show warning if input empty
if (!inputFieldset.reportValidity()) // or use: if (!inputFieldset.value)
return
let toDoStuff = document.createElement('li')
toDoStuff.innerHTML = inputFieldset.value
toDoContainer.append(toDoStuff);
// reset input
inputFieldset.value = '';
})
<h3>Input your activities</h3>
<form>
Input something <input type="text" required id="toDoInput" placeholder="Input your stuff" />
<button id="addButton">+</button>
</form>
<ul id="toDoList">
</ul>
For problem #1:
In line 6 you are creating the let binding toDoStuff which holds a <ul>-element, just to override toDoStuff in line 7 with the current value of the <input>-element. Even if it worked (somehow), I suspect it wouldn't work as you expect, because it would create a completely new list for each todo instead of creating a single list of todos. If I'm right, move the let toDoStuff = document.createElement('ul') line out of your event handler function, create the <ul> right away and .append() it to your toDoContainer (hold a reference to it so that you can append elements to it later).
let toDoContainer = document.getElementById('toDoList');
let toDoStuff = document.createElement('ul');
toDoContainer.append(toDoStuff);
Then, inside the click handler function, create an <li> element that you can append to the <ul>:
addToButton.addEventListener('click', function () {
let toDoListItem = document.createElement('li');
// ... elided
});
The .append() method of an HTMLElement expects to receive another HTMLElement or Node, but you are passing it a String. This means you need to transform that String into a Node before passing it to .append(), and the usual way to do that transformation is via document.createTextNode().
let toDoText = document.createTextNode(inputFieldset.value)
However, you want to insert that Node into a <ul> element and the only child elements of an unordered list should be <li>-elements. This is why we generated the <li> in the previous sections, so all you have to do now is adding the Node to the <li>, then adding the <li> to the <ul>. In code:
addToButton.addEventListener('click', function () {
let toDoListItem = document.createElement('li');
let toDoText = document.createTextNode(inputFieldset.value);
toDoListItem.append(toDoText);
toDoStuff.append(toDoListItem);
});
In regards to the #2 submission problem:
Your button is nested inside a <form> element, so pressing it "naturally" submits the form. What you want to do is to suppress the submission, either via:
calling .preventDefault() on the generated SubmitEvent object of the form
returning false in your event handler function
In favor of a standards way, use .preventDefault(), so we need a reference to the <form> element instead of the <button> as well as changing the event type from 'click' to 'submit':
// ... elided
let addToButton = document.querySelector('form');
// ... elided
addToButton.addEventListener('submit', function (event) { // <-- changed click to submit, added generated event object
event.preventDefault(); // <-- suppress form submission
let toDoListItem = document.createElement('li');
// ... elided, see above
});
Changing the variable names to appropriate ones is left as an excercise ;-)
Example:
let addToButton = document.querySelector('form');
let inputFieldset = document.getElementById('toDoInput');
let toDoContainer = document.getElementById('toDoList');
let toDoStuff = document.createElement('ul');
toDoContainer.append(toDoStuff);
addToButton.addEventListener('submit', function (event) {
event.preventDefault();
let toDoListItem = document.createElement('li');
let toDoText = document.createTextNode(inputFieldset.value);
toDoListItem.append(toDoText);
toDoStuff.append(toDoListItem);
})
<!DOCTYPE html>
<html lang="en">
<head>
<title>la lista</title>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link rel="stylesheet" href="list-style.css"/>
</head>
<body>
<main>
<h1>Ysmael's To-Do List</h1>
<h3>Input your activities</h3>
<form>
Input something<input type="text" required id="toDoInput" placeholder="Input your stuff"/><button id="addButton" type="submit">+</button>
</form>
<div id="toDoList">
</div>
</main>
<script href="todolist.js"></script>
</body>
</html>
One of the solutions to prevent reloading the page after submitting the form is to use even.preventDefault() on submit event. In this way you prevent default browser's behavior. Anyway, to do so, you should add submit event listener. You can also add submitted task to the list from there, therefore I replaced your 'click' event handler with submit.
<script> tag shouldn't have href attribute. It should be src instead.
You are creating <ul> element which is a container for the list of unordered elements. You should create <li> element and append it to <ul> or <ol> container. I have replaced tasks container from <div> to <ul>.
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<title>la lista</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="list-style.css" />
</head>
<body>
<main>
<h1>Ysmael's To-Do List</h1>
<h3>Input your activities</h3>
<form id="toDoForm">
Input something
<input type="text" required id="toDoInput" placeholder="Input your stuff" />
<button id="addButton" type="submit">+</button>
</form>
<ul id="toDoList">
</ul>
</main>
<script src="todolist.js"></script>
</body>
</html>
tasklist.js:
let inputFieldset = document.getElementById('toDoInput');
let toDoContainer = document.getElementById('toDoList');
let toDoForm = document.getElementById('toDoForm');
toDoForm.addEventListener('submit', (event) => {
event.preventDefault();
const task = document.createElement('li');
task.innerText = inputFieldset.value;
toDoContainer.appendChild(task);
inputFieldset.value = '';
})
Change button type to button instead of submit to keep everything from disappearing when it's clicked, and change toDoList element from div to ul and then add tasks as li [list items] rather than ul [a whole unordered list in itself]. Also, you need to change the innerHTML (or innerText) of toDoStuff instead of setting the element itself (so that it remains a li).
let addToButton = document.getElementById('addButton');
let inputFieldset = document.getElementById('toDoInput');
let toDoContainer = document.getElementById('toDoList');
addToButton.addEventListener('click', function(){
let toDoStuff = document.createElement('li');
toDoStuff.innerHTML = inputFieldset.value;
toDoContainer.append(toDoStuff);
inputFieldset.value = "";//clear field
})
//so that "enter" does the same as addToButton instead of submit
inputFieldset.addEventListener("keydown", function(event) {
if (event.key === "Enter") {
event.preventDefault();
addToButton.click();
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<title>la lista</title>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link rel="stylesheet" href="list-style.css"/>
</head>
<body>
<main>
<h1>Ysmael's To-Do List</h1>
<h3>Input your activities</h3>
<form>
Input something<input type="text" required id="toDoInput" placeholder="Input your stuff"/><button id="addButton" type="button">+</button>
</form>
<ul id="toDoList">
</ul>
</main>
<script href="todolist.js"></script>
</body>
</html>
I've also added a line to clear the field [for the next task] after a task has been added, and another event listener to the text input because "enter" key can also register as submit - but now, instead of everything disappearing on enter, it simulates clicking the add button.
I changed your code. The problems are 3 in number.
you have button type submit, this submits the form and the form then requires an action to handle the submit, this is typically used to send data to other pages.(dont quote me on that, i never use it)
you made toDoStuff get the value of the input thus overriding the create element.
you had a div as a container for a created ul when you want to have a ul as container for a created li.
Here is the changed html:
<body>
<main>
<h1>Ysmael's To-Do List</h1>
<h3>Input your activities</h3>
<form>
Input something<input type="text" required id="toDoInput" placeholder="Input your stuff"/><button id="addButton" type="button">+</button>
</form>
<ul id="toDoList">
</ul>
</main>
</body>
And here is the changed Javascript:
let addToButton = document.getElementById('addButton')
let inputFieldset = document.getElementById('toDoInput')
let toDoContainer = document.getElementById('toDoList')
addToButton.addEventListener('click', () => {
let toDoStuff = document.createElement('li')
toDoStuff.innerHTML = inputFieldset.value
toDoContainer.append(toDoStuff)
})
Good luck and happy coding, dont let a setback make you give up!
Bind the <form> to the "submit" event. Details are commented in example.
// Reference <form>
const todo = document.forms.todo;
// Reference <input>
const add = todo.elements.add;
// Reference <ul>
const list = document.querySelector(".list");
/**
* Bind <form> to "submit" event
* Stop <form> from sending data and blanking out the page
* Create <li> which is required in a <ul>
* Add the value of <input> as the text of <li>
* Add <li> to <ul>
* Clear the <form> to prevent accidental clicking
*/
todo.addEventListener('submit', function(event) {
event.preventDefault();
const item = document.createElement('li')
item.textContent = add.value
list.append(item);
this.reset();
});
<main>
<!-- Add #id or [name] to <form> -->
<form id="todo">
<fieldset>
<legend>Ysmael's To-Do List</legend>
<!-- Add <label> and [for="{<input> #id}"] -->
<label for="add">Enter Task: </label>
<input id="add" type="text" required>
<!-- A plain <button> inside a <form> will trigger "submit" -->
<button>+</button>
</fieldset>
</form>
<ul class="list"></ul>
</main>

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>

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>

Categories