Why the input value wont update ? when i click the send button? - javascript

I try to run the code it works for the first time but in the second time it won't work I don't know why ?
I want to make it in a way that I can send several messages over and over
var message = document.querySelector('.container');
var btn = document.getElementById('btn');
var inpt = document.getElementById('txt');
function AddMessage() {
if (String(inpt.value) != '' && isNaN(inpt.value) == true) {
message.innerHTML += `<p>${inpt.value} </p>`;
inpt.value = '';
}
}
input {
outline: none;
}
<div class="container">
<input type="text" value="" id="txt">
<button id="btn" onclick="AddMessage()">send</button>
<p>whats your name ?</p>
</div>

Issues with .innerHTML
You are assigning to .innerHTML. This causes recreation of the element's descendants (see innerHTML "On setting..."):
const oldReference = document.getElementById("element");
document.body.innerHTML += ""; // Assigning to innerHTML
const newReference = document.getElementById("element");
const isSameElement = oldReference === newReference;
console.log({ isSameElement });
<div id="element">
As you can see, the old references btn and inpt won't be the elements currently in the DOM.
Sidenote: Parsing .innerHTML may be quite time-consuming, and its use with user input is a security issue.
Security considerations
Especially with user input you shouldn't use .innerHTML, because that is an easy way to insert scripts into your webpage:
document.body.addEventListener("click", evt => {
if (!evt.target.closest("button")) return;
const input = document.querySelector("input");
document.body.innerHTML += input.value;
});
pre{padding:2px 4px;border:1px solid;width:min-content}
<input><button>Insert</button>
<p>Try to input this:</p>
<pre><code><img src=""
onerror="console.log('any script here!')"></code></pre>
<p>Then look into your browser console.
Alternatives for .innerHTML
If you want to add elements, you can use document.createElement(), Element.append(), and Node.textContent:
const input = document.querySelector("input");
document.querySelector("button").addEventListener("click", evt => {
const p = document.createElement("p");
p.textContent = input.value;
document.body.append(p);
input.value = "";
const currentInput = document.querySelector("input");
console.log("Is same input?", input === currentInput);
});
<input><button>Insert</button>
<p>Also try adding some HTML, for example: <code><span>Test</span>

Since your output element is the wrapper for all of the other elements, when you do this you are overwriting all of those elements:
message.innerHTML += `<p>${inpt.value} </p>`;
Visually (and perhaps even intuitively) this has no noticeable effect. But what it does is create entirely new elements which no longer correspond to your btn and inpt variables. Which leaves you interacting with stale objects that don't represent anything on the screen.
Probably the simplest approach would be to create a more specific output element. For example, add another <div> in your container and output to that:
var message = document.getElementById('message'); // reference new element
var btn = document.getElementById('btn');
var inpt = document.getElementById('txt');
function AddMessage() {
if (String(inpt.value) != '' && isNaN(inpt.value) == true) {
message.innerHTML += `<p>${inpt.value} </p>`;
inpt.value = '';
}
}
input {
outline: none;
}
<div class="container">
<input type="text" value="" id="txt">
<button id="btn" onclick="AddMessage()">send</button>
<p>whats your name ?</p>
<div id="message"></div> <!-- new element -->
</div>

This line message.innerHTML += ...
equals to message.innerHTML = message.innerHTML + ..., it assigns something new to message.innerHTML, in other words, it rewrites the content, thus references of btn and inpt are lost, the originals are overriden.
var message = document.querySelector('.container');
var btn = document.getElementById('btn');
var inpt = document.getElementById('txt');
var output = document.getElementById('output');
function AddMessage() {
console.log('addMessage')
if (String(inpt.value) != '' && isNaN(inpt.value) == true) {
output.innerText=inpt.value;
inpt.value = ''
}
}
input {
outline: none;
}
<div class="container">
<input type="text" value="" id="txt" placeholder="write your message here">
<button id="btn" onclick="AddMessage()">send</button>
<p>whats your name ?</p>
<p id="output"></p>
</div>

You can update only inner html for answer, not the full block with input
<!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>
<style>
input{
outline: none;
}
</style>
<div class="container">
<input type="text" value="" id="txt">
<button id="btn" onclick="AddMessage()">send</button>
<p>whats your name ?</p>
<p id="answer"></p>
</div>
<script>
var message = document.querySelector('.container');
var btn = document.getElementById('btn');
var inpt = document.getElementById('txt');
var answer = document.getElementById('answer');
function AddMessage(){
if( String(inpt.value) != '' && isNaN(inpt.value) == true )
{
answer.innerHTML = `<p>${inpt.value} </p>`;
inpt.value = '';
}
}
</script>
</body>
</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>Document</title>
</head>
<body>
<style>
input{
outline: none;
}
</style>
<div class="container">
<input type="text" value="" id="txt" name="txt">
<button id="btn" onclick="AddMessage()">send</button>
<p>whats your name ?</p>
<ul id="list">
</ul>
</div>
<script>
var message = document.querySelector('.container');
var btn = document.getElementById('btn');
var inpt = document.getElementById('txt');
var list = document.getElementById('list');
let myList = "";
function AddMessage(){
if( String(inpt.value) !== '' && isNaN(inpt.value) == true )
{
myList +=`<li>${inpt.value}</li>`;
list.innerHTML = myList;
}
}
</script>
</body>
</html>

Related

I want to save the data in a textbox created repeatedly in JavaScript using webstorage

this is my code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>CV Information</title>
<link rel="stylesheet" href="StyleSheet1.css" />
</head>
<body>
<header><b>CV Information</b></header>
<!--<script src="Script1.js"></script>-->
<div class="mydiv">
<form action="CV_Viewer.html">
<fieldset id="field">
<div class="scrollable" id="scroll">
<header>Languages</header><br />
<label for="mLan">Your Mothertoungue:</label>
<input type="text" id="mLan" placeholder="Primary Language.." name="name" pattern="[A-Za-z ]{3,}" required><br><br>
<input type="button" id="plus" onclick="addTextBox()" class="plus" value="+ other languages..." name="plus" />
</div>
<div style="position: static">
<input type="submit" onclick="webstorage()" class="hov" style="margin-top:30px" value="Next">
</div>
</fieldset>
</form>
</div>
<footer>
Copyright©2022 Rami Joulani
</footer>
<script>
let b = 1;
let q=0;
const array = [];
function addTextBox() {
b++;
const textBox = document.createElement("INPUT");
textBox.setAttribute("type", "text");
textBox.setAttribute("placeholder", "Any Other Language...");
textBox.setAttribute("pattern", "[A-Za-z ]{3,}");
textBox.setAttribute("style", "margin-top:35px;");
textBox.setAttribute("id",q);
const div = document.getElementById("scroll");
div.appendChild(textBox);
var plus = document.getElementById("plus");
div.insertBefore(textBox, plus);
array[q] = textBox.value;
console.log(array[q]);
q++;
return fieldSet();
}
function fieldSet() {
const radio1 = document.createElement("input");
radio1.setAttribute("type", "radio");
radio1.setAttribute("id", "rad1");
radio1.setAttribute("name", "connected");
const div = document.getElementById("scroll");
var plus = document.getElementById("plus");
div.appendChild(radio1);
div.insertBefore(radio1, plus);
const begg = document.createElement("label");
begg.setAttribute("for", "rad1");
const begginer = document.createTextNode("Begginer");
begg.appendChild(begginer);
div.appendChild(begg);
div.insertBefore(begg, plus);
const radio2 = document.createElement("input");
radio2.setAttribute("type", "radio");
radio2.setAttribute("id", "rad2");
radio2.setAttribute("name", "connected")
div.appendChild(radio2);
div.insertBefore(radio2, plus);
const inter = document.createElement("label");
inter.setAttribute("for", "rad2");
const intermadiate = document.createTextNode("Intermadiate");
inter.appendChild(intermadiate);
div.appendChild(inter);
div.insertBefore(inter, plus);
const radio3 = document.createElement("input");
radio3.setAttribute("type", "radio");
radio3.setAttribute("id", "rad3");
radio3.setAttribute("name", "connected")
div.appendChild(radio3);
div.insertBefore(radio3, plus);
const flu = document.createElement("label");
flu.setAttribute("for", "rad3");
const fluent = document.createTextNode("Fluent");
flu.appendChild(fluent);
div.appendChild(flu);
div.insertBefore(flu, plus);
plus.setAttribute("style", "margin-top:20px;")
if(b==4) {
plus.hidden=true;
}
}
function webstorage() {
localStorage.setItem("mothTong", document.getElementById("mLan").value);
}
</script>
</body>
</html>
I changed it multiple times when I tried to solve it
how can I save textBox value and the radio button values separately though they are created with the same attribute
it might be simple but I just couldn't figure it out.
Don't point out to some missing stuff but if you please tell me how is it possible to do it depending on the general form of the code.

Multiply output by inputs

I'm trying to create a list based off of 2 input fields. The first input will be a name and the second an integer.
What I'm trying to achieve is having the name displayed multiplied by the amount of the input integer. I have got the name to display based off the input, but have been unable to have it displayed multiple times based on the input integer.
Here's an example image of what I'm looking to achieve
<html>
<head>
<style>
input {
display: block;
}
#msgs {
margin-bottom: 24px;
}
</style>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<input type="text" value="Michael" id="name" />
<input type="text" value="5" id="count" />
<input type="button" value="add to list" id="add" />
<div id="list"> </div>
</body>
<script>
document.getElementById("add").onclick = function() {
var text = document.getElementById("name").value;
var div = document.createElement("div");
div.textContent = text;
document.getElementById("list").appendChild(div);
document.getElementById("name").value = ""; // clear the value
}
</script>
</html>
Fiddle: https://jsfiddle.net/grnct2yz/
<html>
<head>
<style>
input {
display: block;
}
#msgs {
margin-bottom: 24px;
}
</style>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<input type="text" value="Michael" id="name" />
<input type="number" value="5" id="count" />
<input type="button" value="add to list" id="add" />
<div id="list"> </div>
</body>
<script>
document.getElementById("add").onclick = function() {
var text = document.getElementById("name").value;
for(let i = 0; i < document.getElementById("count").value; i++) {
var div = document.createElement("div");
div.textContent = text;
document.getElementById("list").appendChild(div);
}
document.getElementById("name").value = ""; // clear the value
}
</script>
</html>
I have added a loop and changed the input type to number so we are sure that it's going to insert a number in the loop. Is this what you wanted?
What the code I added does is cycling a number of times equal to the number inputted and then executing the code you wrote.
for loops work this way:
you set an initial statement that is executed at the beginning of the loop, only once (let i = 0 sets a new iterable variable i),
then you set a condition that is checked before every iteration of the loop to make it run (i < document.getElementById("count").value checks that it executes up to and not more than X times, where X is the number inputted),
then you set an operation to be executed at the end of each loop (i++ increments the value of i by one).
Here is another way of doing it:
const name=document.getElementById("name"),
count=document.getElementById("count"),
list=document.getElementById("list");
document.getElementById("add").onclick = function() {
list.insertAdjacentHTML("beforeend",[...Array(+count.value)].map(s=>`<div>${name.value}</div>`).join(""))
name.value = ""; // clear the value
}
<input type="text" value="Michael" id="name" /><br>
<input type="text" value="5" id="count" /><br>
<input type="button" value="add to list" id="add" />
<div id="list"> </div>
Just your Improved code based on your needs we can achieve this in many ways.
<html>
<head>
<style>
input {
display: block;
}
#msgs {
margin-bottom: 24px;
}
</style>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<input type="text" value="Michael" id="name" />
<input type="text" value="5" id="count" />
<input type="button" value="add to list" id="add" />
<div id="list"> </div>
<script>
document.getElementById("add").onclick = function() {
var text = document.getElementById("name").value;
var count = document.getElementById("count").value;
if (parseInt(count) != 'NaN') {
var list = document.getElementById("list");
while (list.firstChild) {
list.removeChild(list.firstChild);
}
count = parseInt(count);
for (var i = 0; i < count; i++) {
var div = document.createElement("div");
div.textContent = text;
document.getElementById("list").appendChild(div);
}
}
}
</script>
</body>
</html>

How to call function when input value changes?

I have tried to find a way to call a function when the value of the input changes, but so far I haven't found anything. All of the things I have tried seemed to work but didn't.
Html:
var funds = 500;
document.getElementById("submit").onclick = function() {
}
function AP() {
if (document.getElementById("p").checked) {
document.getElementById("AP").innerHTML = "%";
} else {
document.getElementById("AP").innerHTML = "";
}
}
//right here I'd like the function to call.
<!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>Rng Crypto</title>
</head>
<body>
<header>
<h1>Crypto ran from randomness!</h1>
</header>
<div>
<input type="radio" name="AP" id="a" onchange="AP()" checked>Absolute<input type="radio" name="AP" id="p" onchange="AP()">Percent<br>
<input type="number" id="input" HERE TO ADD THINGY>
<p id="AP" style="display:inline;"></p><br>
<button id="submit">Submit</button>
</div>
<script src="RngCrypto.js"></script>
</body>
</html>
The things that I have tried are:
<input type="number" id="input" onchange="input()">
<input type="number" id="input" oninput="input()">
<input type="number" id="input" onkeyup="input()">
document.getElementById("input").onchange=input();
document.getElementById("input").oninput=input();
const inputEle = document.querySelector("#input");
inputEle.addEventListener('input', function(e) {
console.log(e.target.value);
})
<input type="text" id="input">
Have you tried adding the 'change' event on the input element.
Edit: adding 'input' eventListener, is one more way to achieve this result.
(refer following code)
var funds = 500;
document.getElementById("submit").onclick = function() {
}
function AP() {
if (document.getElementById("p").checked) {
document.getElementById("AP").innerHTML = "%";
} else {
document.getElementById("AP").innerHTML = "";
}
}
//right here I'd like the function to call.
document.queryselector("#input").addEventlistener('change', function(e) {
console.log(e.target.value;)
})
When I got you right this is basically what you are looking for:
<input class="js-radio-button" type="radio" name="ab" value="absolute"> Absolute<br>
<input class="js-radio-button" type="radio" name="ab" value="percent"> Percent<br>
<button class="js-check-selection">CHECK</button>
<div>
<span>Result is:</span> <span id="result"></span>
</div>
in your javascript you have:
function checkSelectedRadio() {
// get your radios having the name 'ab'
const radios = document.querySelectorAll('input[type=radio][name=ab]');
// reset result container
document.getElementById('result').innerHTML = '';
// loop through the radios
for (let i = 0; i < radios.length; i += 1) {
// check for each radio if it was selected
if (radios[i].checked) {
// set the value of the selected radio to your result container
document.getElementById('result').innerHTML = `Value: ${radios[i].value}`;
// if you need more logic:
if (radios[i].value === 'absolute') {
// do something here if 'absolute' was checked
} else if (radios[i].value === 'percent') {
// do something here if 'percent' was checked
}
}
}
}
// get your button to check radio status like this or fire the function above by your onchange handler
const checkButton = document.querySelector('.js-check-selection');
checkButton.addEventListener('click', checkSelectedRadio);
EDIT after reading your comment:
To detect change of your input field it works like this:
<input type="number" id="input" value="1">
In your JS:
const field = document.querySelector('#input');
function inputCheck() {
console.log('input changed');
// or do something else
}
field.addEventListener('change', inputCheck);

Need making super simple HTML/Javscript comment section for a small food shopping website for windows 10 laptop thanks please thank you very much

I need help making a comment section for my webpage.
I've tried document.createElement and .appendChild() but it's not working out for me. I have attached what I have now.
function leaveComment(){
let name = String(document.getElementById('name').value);
let topic = String(document.getElementById('topic').value);
let comment = String(document.getElementById('commenttt').value);
let userbox = document.createElement("div")
userbox.className = "userbox"
let pfp = document.createElement("div")
pfp.className = "pfp"
let commentation = document.createElement("div")
commentation.className = "comment"
let image = document.createElement("img")
image.setAttribute('src', 'multimedia/images/pfp.jpg');
image.setAttribute('alt', 'pic');
let username = document.createElement("h2")
let heading = document.createElement("h3")
let text = document.createElement("p")
const newName = document.createTextNode(name);
const newTopic = document.createTextNode(topic);
const newCom = document.createTextNode(comment);
pfp.appendChild(image)
pfp.appendChild(newName)
comment.appendChild(newTopic)
comment.appendChild(text)
userbox.appendChild(pfp)
userbox.appendChild(commentation)
var element = document.getElementsByClassName("comments")
element.appendChild(userbox);
}
Your issue lies in here
var element = document.getElementsByClassName("comments")
element.appendChild(userbox);
getElementsByClassName returns something called HTMLCollection which does not have appendChild method.
For the above code to work you need to call it like this
var element = document.getElementsByClassName("comments")
element[0].appendChild(userbox);
Firstly, that code could use some more whitespace for readability. Try grouping related lines and separating the groups with an empty line.
You need to actually reference the right elements and actually fill the elements once you have created them. I think this does what you want:
function leaveComment(){
let name = String(document.getElementById('name').value);
let topic = String(document.getElementById('topic').value);
let comment = String(document.getElementById('commenttt').value);
let userbox = document.createElement("div")
userbox.className = "userbox"
let pfp = document.createElement("div")
pfp.className = "pfp"
let commentation = document.createElement("div")
commentation.className = "comment"
let image = document.createElement("img")
image.setAttribute('src', 'multimedia/images/pfp.jpg');
image.setAttribute('alt', 'pic');
let username = document.createElement("h2")
let heading = document.createElement("h3")
let text = document.createElement("p")
text.appendChild(document.createTextNode(comment))
username.innerHTML = name;
heading.innerHTML = topic;
const newCom = document.createTextNode(comment);
pfp.appendChild(image)
pfp.appendChild(username)
commentation.appendChild(heading)
commentation.appendChild(text)
userbox.appendChild(pfp)
userbox.appendChild(commentation)
var element = document.getElementById("comment-section")
element.appendChild(userbox);
}
.pred {
width: 40%;
float: left;
}
.comments {
width: 50%;
float: left;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8"/>
<meta name="googleapis" content="noindex"/>
<link rel="stylesheet" type="text/css" href="stylesheet.css"/>
<link rel="preconnect" href="https://fonts.gstatic.com">
<script src="script.js"></script>
<link href="https://fonts.googleapis.com/css2?family=KoHo:ital,wght#0,400;0,600;1,300&display=swap" rel="stylesheet">
<title>test</title>
</head>
<body>
<div class="pred">
<h1>Leave your comment!</h1>
<br>
<br>
<form class="" onsubmit="leaveComment()" method="post">
<p>Nickname or Name</p> <input id="name" required="required" type="text" name="" value="">
<br>
<p>Discussion Topic(s)-</p><input id="topic" required="required" type="text" name="" value="">
<br>
<br>
<p>Comments: </p><textarea id="commenttt" required="required" name="name" rows="8" cols="20"></textarea>
<button type="button" onclick="leaveComment()" name="button">Comment!</button>
</form>
</div>
<div class="comments" id="comment-section">
<h1>Comments</h1>
<hr>
<div class="userbox">
<div class="pfp">
<img src="multimedia/images/pfp.jpg" alt="p">
<h2>Bob</h2>
</div>
<div class="comment">
<h3>Random Topic Haha</h3>
<p>Random topic sucks</p>
</div>
</div>
</div>
</body>
</html>
Sidenote:
I strongly suggest looking into webcomponents, E.g. LitElement
Makes everything much more organized.

JavaScript Strike Through innerText Not Working

I am trying to create a To Do list and am having troubles strikingthrough a created To Do item. A "Click if Completed" button appears on the right side of the created to-do item which, when clicked, should strikeout the text. I am pretty sure it is an issue with the (e.target.newToDo.innerText.strike())
Do I need to create a variable for the newToDo.innerText? Am I still able to create one since I have created (newToDo.innerText = input.value) in the function earlier?
Just want to say that the people on this website are amazing and have helped a ton. Thank you in advance!
const form = document.querySelector('#addToDo');
const input = document.querySelector('#theToDo');
const todolist = document.querySelector('#todolist');
form.addEventListener('submit',function(e){
e.preventDefault();
const newToDo = document.createElement('li');
const removeBtn = document.createElement('button');
const completeBtn = document.createElement('button');
newToDo.innerText = input.value;
removeBtn.innerText = 'Click to Remove';
completeBtn.innerText = 'Click if Completed';
newToDo.appendChild(completeBtn);
newToDo.appendChild(removeBtn);
input.value = '';
todolist.appendChild(newToDo);
completeBtn.addEventListener("click", function(e){
e.target.newToDo.innerText.strike();
})
removeBtn.addEventListener("click", function(e){
e.target.parentElement.remove();
})
})
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<h1>To Do List:</h1>
<ul id="todolist">
</ul>
<form action="" id="addToDo" name="addToDo">
<input type="text" id="theToDo"
name="addToDo"
placeholder="Add to the list here">
<button type="submit">Submit</button>
</form>
<script src=Test.js></script>
</body>
</html>
Why wasn't your code working
Your code wasn't working because of e.target.newToDo.innerText.strike() this does not target the li (parent element) and you need to set the innerText to the striked innerText or it will not show.
Why you should not use strike()
It is not good practice to edit styles within JS and the <strike> tag is not supported in HTML5.
Instead, create a CSS class like this:
.strike {
text-decoration: line-through;
}
Then append the .strike class to the HTML element.
Solution
const form = document.querySelector('#addToDo');
const input = document.querySelector('#theToDo');
const todolist = document.querySelector('#todolist');
form.addEventListener('submit',function(e){
e.preventDefault()
todolist.innerHTML += `<li>
<span>${input.value}</span>
<button onclick="strikeItem(this)">strike</button>
<button onclick="removeItem(this)">remove</button>
</li>`
})
function strikeItem(ele) {
const itemTextEle = ele.parentElement.querySelector('span')
itemTextEle.innerHTML = itemTextEle.innerText.strike()
}
function removeItem(ele) {
ele.parentElement.remove()
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<h1>To Do List:</h1>
<ul id="todolist">
</ul>
<form action="" id="addToDo" name="addToDo">
<input type="text" id="theToDo"
name="addToDo"
placeholder="Add to the list here">
<button type="submit">Submit</button>
</form>
<script src=Test.js></script>
</body>
</html>
This is a bit easier to read and is less code to write.
This solution uses the strike() function to show you how to use it I would try appending a class instead.
Append your newToDo to todolist and change the innerHtml on click function call:
const form = document.querySelector('#addToDo');
const input = document.querySelector('#theToDo');
const todolist = document.querySelector('#todolist');
form.addEventListener('submit', function(e) {
e.preventDefault();
const newToDo = document.createElement('li');
const removeBtn = document.createElement('button');
const completeBtn = document.createElement('button');
newToDo.id = 'new_todo';
newToDo.innerText = input.value;
removeBtn.innerText = 'Click to Remove';
completeBtn.innerText = 'Click if Completed';
todolist.append(newToDo);
todolist.appendChild(completeBtn);
todolist.appendChild(removeBtn);
input.value = '';
completeBtn.addEventListener("click", function(e) {
var todo = document.querySelector('#new_todo');
var todoText = '<del>' + todo.innerText + '</del>';
todo.innerHTML = todoText;
})
removeBtn.addEventListener("click", function(e) {
e.target.parentElement.remove();
})
})
see the working fiddle here: https://jsfiddle.net/khushboo097/uak3f5s2/20/
const form = document.querySelector('#addToDo');
const input = document.querySelector('#theToDo');
const todolist = document.querySelector('#todolist');
form.addEventListener('submit',function(e){
e.preventDefault();
const newToDo = document.createElement('li');
const removeBtn = document.createElement('button');
const completeBtn = document.createElement('button');
newToDo.innerText = input.value;
removeBtn.innerText = 'Click to Remove';
completeBtn.innerText = 'Click if Completed';
newToDo.appendChild(completeBtn);
newToDo.appendChild(removeBtn);
input.value = '';
todolist.appendChild(newToDo);
completeBtn.addEventListener("click", function(e){
e.target.parentElement.style.textDecoration="line-through";
})
removeBtn.addEventListener("click", function(e){
e.target.parentElement.remove();
})
})
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<h1>To Do List:</h1>
<ul id="todolist">
</ul>
<form action="" id="addToDo" name="addToDo">
<input type="text" id="theToDo"
name="addToDo"
placeholder="Add to the list here">
<button type="submit">Submit</button>
</form>
<script src=Test.js></script>
</body>
</html>
Do it like this:
const form = document.querySelector('#addToDo');
const input = document.querySelector('#theToDo');
const todolist = document.querySelector('#todolist');
form.addEventListener('submit', function(e) {
e.preventDefault();
const newToDo = document.createElement('li');
const newToDoName = document.createElement('span');
const removeBtn = document.createElement('button');
const completeBtn = document.createElement('button');
newToDoName.innerText = input.value;
removeBtn.innerText = 'Click to Remove';
completeBtn.innerText = 'Click if Completed';
newToDo.appendChild(newToDoName);
newToDo.appendChild(completeBtn);
newToDo.appendChild(removeBtn);
input.value = '';
todolist.appendChild(newToDo);
completeBtn.addEventListener("click", function(e) {
newToDo.innerHTML = newToDoName.innerText.strike();
})
removeBtn.addEventListener("click", function(e) {
e.target.parentElement.remove();
})
})
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<h1>To Do List:</h1>
<ul id="todolist">
</ul>
<form action="" id="addToDo" name="addToDo">
<input type="text" id="theToDo" name="addToDo" placeholder="Add to the list here">
<button type="submit">Submit</button>
</form>
<script src=Test.js></script>
</body>
</html>

Categories

Resources