I am very new to JavaScript so I apologize in advance for this question! It's still hard for me to 'read' where I am going wrong.
I am trying to practice simple logic where there is a form with two inputs. Then, what is typed into the input is appended to the page after the person presses submit on the form. The person's inputs are structured as li being added to a ul.
I can make this part work fine on its own. However, I am trying to append not just an li, but a delete button with each li. Then, I want the delete button to be able to delete its associated li.
Here is my logic, but I know it is not right...
const form = document.querySelector('form');
const list = document.querySelector('#list');
form.addEventListener('submit', function(e) {
e.preventDefault();
let product = form.elements.product;
let qty = form.elements.qty;
const li = document.createElement('li');
const button = document.createElement('button')
li.innerText = `${product.value} ${qty.value}`;
button.textContent = "Delete"
li.appendChild('button')
list.appendChild(li);
product.value = '';
qty.value = '';
button.addEventListener('click', function() {
e.target.remove
})
})
<h1>Grocery List</h1>
<form action="/nowhere">
<label for="item">Enter A Product</label>
<input type="text" id="product" name="product">
<label for="item">Enter A Quantity</label>
<input type="number" id="qty" name="qty">
<button>Submit</button>
</form>
<ul id="list"></ul>
<li>Test</li>
You have syntax errors, missing () and missing (e)
Too many quotes ('button') and you do not want to delete the target, but its containing li
const form = document.querySelector('form');
const list = document.getElementById('list');
const product = document.getElementById('product');
const quantity = document.getElementById('qty');
form.addEventListener('submit', function(e) {
e.preventDefault();
const prd = product.value,
qty = +quantity.value; // cast to number
if (prd === "" || qty === 0) return; // nothing to add
product.value = '';
quantity.value = '';
const li = document.createElement('li');
const delBut = document.createElement('button')
li.innerText = `${prd} ${qty}`;
delBut.textContent = "Delete"
li.appendChild(delBut)
list.appendChild(li);
delBut.addEventListener('click', function(e) {
e.target.closest('li').remove()
})
})
<h1>Grocery List</h1>
<form action="/nowhere">
<label for="item">Enter A Product</label>
<input type="text" id="product" name="product">
<label for="item">Enter A Quantity</label>
<input type="number" id="qty" name="qty">
<button>Submit</button>
</form>
<ul id="list"></ul>
Related
I am trying to get all checked checkboxes and create li elements with them. I want the li elements to show up as soon as the checkboxes are checked.
And can I do that without using value attribute in input? I already looked up there is a way to do that with value but that doesn't work with my code.
I have this code
const checkboxes = document.getElementsByTagName('input').type == 'checkbox';
function getChecked() {
let checked = [];
for (let i = 0; i < checkboxes.length; i++) {
let checkbox = checkboxes[i];
if (checkbox.checked) {
const rightBox = document.getElementsByClassName('main-container-2')[0];
const newDiv = document.createElement('div');
rightBox.appendChild(newDiv);
const ul = document.createElement('ul');
newDiv.appendChild(ul);
const li = document.createElement('li');
ul.appendChild(li);
const label = document.createElement('label');
li.innerHTML = label.innerHTML;
}
}
return checked;
};
getChecked();
<div class="article-main">
<div class="article-left">
<div>
<input type="checkbox" id="checkbox1">
<label for="checkbox1">Onion</label>
</div>
<div>
<input type="checkbox" id="checkbox2">
<label for="checkbox2">Spring Onion</label>
</div>
<div>
<input type="checkbox" id="checkbox3">
<label for="checkbox3">Egg</label>
</div>
</div>
</div>
This image is my goal.
Your checkboxes select was wrong, so I fixed it in the first place.
You should add a onclick function to all of your checkboxes.
Inside that function you should empty the list and loop trough all checkboxes.
When a checkbox is checked, then add a li to your list.
The code below works.
const checkboxes = document.querySelectorAll('input[type=checkbox]');
function getChecked() {
let checked = [];
const ul = document.getElementById('ingredients');
ul.innerHTML = "";
for (let i = 0; i < checkboxes.length; i++) {
let checkbox = checkboxes[i];
if (checkbox.checked) {
const li = document.createElement('li');
li.innerHTML = document.querySelector('label[for="' + checkbox.id + '"]').textContent.trim();
ul.appendChild(li);
}
}
return checked;
};
<div class="article-main">
<div class="article-left">
<div>
<input type="checkbox" onclick="getChecked()" id="checkbox1">
<label for="checkbox1">Onion</label>
</div>
<div>
<input type="checkbox" onclick="getChecked()" id="checkbox2">
<label for="checkbox2">Spring Onion</label>
</div>
<div>
<input type="checkbox" onclick="getChecked()" id="checkbox3">
<label for="checkbox3">Egg</label>
</div>
</div>
</div>
<br/>
your ingredients
<ul id="ingredients">
</ul>
I give you an example for your reference:
document.addEventListener("DOMContentLoaded", function(event) {
const checkBoxes = document.querySelectorAll("input[type=checkbox]");
for (let i = 0; i < checkBoxes.length; i++) {
let checkBox = checkBoxes[i];
checkBox.addEventListener("click", e => {
if (e.target.checked) {
const rightBox = document.getElementsByClassName('main-container-2')[0];
const newDiv = document.createElement('div');
rightBox.appendChild(newDiv);
const ul = document.createElement('ul');
newDiv.appendChild(ul);
const li = document.createElement('li');
ul.appendChild(li);
let l=e.target.nextElementSibling;
li.innerHTML = l.innerHTML;
}
});
}
});
<div class="article-main">
<div class="article-left">
<div>
<input type="checkbox" id="checkbox1">
<label for="checkbox1">Onion</label>
</div>
<div>
<input type="checkbox" id="checkbox2">
<label for="checkbox2">Spring Onion</label>
</div>
<div>
<input type="checkbox" id="checkbox3">
<label for="checkbox3">Egg</label>
</div>
</div>
</div>
<div class="main-container-2">
</div>
I created a list to add items to it, however, I'm also trying to add a delete button to remove any Item that's being added to my list, but I can't get it to work,
see snippet below
const form = document.querySelector("form");
const product = document.querySelector("#fruitName");
const quantity = document.querySelector("#qty");
const list = document.querySelector("#list");
form.addEventListener("submit", (e) => {
e.preventDefault();
const item = fruitName.value;
const numOfItmes = qty.value;
const newLi = document.createElement("li");
newLi.innerText = `${numOfItmes} ${item}`;
list.appendChild(newLi);
button.addEventListener("click", () => {
const button = document.createElement("button");
button.textContent = "X";
li.appendChild(button);
});
form.qty.value = "";
form.fruitName.value = "";
});
button {
width: 100px;
height: 100px;
margin: 20px;
}
#fruit {
width: auto;
height: auto;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="color.css" />
<title>Document</title>
</head>
<body>
<h1>Welcome!</h1>
<form action="test">
<label for="item">Enter Product</label>
<input type="text" id="fruitName" />
<label for="item">Enter A Quantity</label>
<input type="number" id="qty" name="qty" />
<button id="fruit">Submit</button>
</form>
<ul id="list"></ul>
<script src="color.js"></script>
</body>
</html>
I created a list to add items to it, however, I'm also trying to add a delete button to remove any Item that's being added to my list, but I can't get it to work,
see my code below
const form = document.querySelector("form");
const product = document.querySelector("#fruitName");
const quantity = document.querySelector("#qty");
const list = document.querySelector("#list");
form.addEventListener("submit", (e) => {
e.preventDefault();
const item = fruitName.value;
const numOfItmes = qty.value;
const newLi = document.createElement("li");
newLi.innerText = `${numOfItmes} ${item}`;
list.appendChild(newLi);
button.addEventListener("click", () => {
const button = document.createElement("button");
button.textContent = "X";
li.appendChild(button);
});
form.qty.value = "";
form.fruitName.value = "";
});
<h1>Welcome!</h1>
<form action="test">
<label for="item">Enter Product</label>
<input type="text" id="fruitName" />
<label for="item">Enter A Quantity</label>
<input type="number" id="qty" name="qty" />
<button id="fruit">Submit</button>
</form>
<ul id="list"></ul>
can anyone help me with this?
You were creating the li's child button element in the wrong place, and you weren't removing the li at all when it was clicked. Here's the working code:
const form = document.querySelector("form");
const product = document.querySelector("#fruitName");
const quantity = document.querySelector("#qty");
const list = document.querySelector("#list");
form.addEventListener("submit", (e) => {
e.preventDefault();
const item = fruitName.value;
const numOfItmes = qty.value;
const newLi = document.createElement("li");
newLi.innerText = `${numOfItmes} ${item}`;
list.appendChild(newLi);
// create button outside of event listener
const button = document.createElement("button");
button.textContent = "X";
newLi.appendChild(button);
// remove the created li element when button is clicked
button.addEventListener("click", () => {
newLi.remove();
});
form.qty.value = "";
form.fruitName.value = "";
});
<h1>Welcome!</h1>
<form action="test">
<label for="item">Enter Product</label>
<input type="text" id="fruitName" />
<label for="item">Enter A Quantity</label>
<input type="number" id="qty" name="qty" />
<button id="fruit">Submit</button>
</form>
<ul id="list"></ul>
i've tried to make an simple app, its only user input and show the output, and now i tried to make local Storage. can anyone help me plis
this is my code
html
<aside class="input">
<form action="#" id="form">
<div class="form-section">
<label for="name">Input Name</label>
<input type="text" id="name">
</div>
<div class="form-section">
<label for="title">Input Name</label>
<input type="text" id="title">
</div>
<button class="submit-btn">Submit</button>
</form>
</aside>
JavaScript
localStorage = "itsStorage";
function addVal() {
const takeName = document.getElementById("name").value;
const takeTittle = document.getElementById("title").value;
const wrapIt = wrapper(takeName,takeTittle);
const list = document.getElementById("list");
localStorage.setItem(takeName, takeTittle);
}
function wrapper(itsName, itsTittle) {
const name = document.createElement("h2");
name.innerText = itsName;
const tittle = document.createElement("p");
tittle.innerText = itsTittle;
const div = document.createElement("div");
div.classList.add("list");
div.append(name, tittle);
const outList = document.querySelector(".list-output");
outList.append(div);
localStorage.getItem(name, tittle);
}
Something more like this
Use stringify to store an array and parse to get it back
I could not test it since Stacksnippets do not allow localStorage
Also I did not code a delete button
If you want one, you need to delegate
There were several other issues I tried to fix, study the code
window.addEventListener("load", function() {
const outList = document.getElementById("container");
const list = localStorage.getItem("list");
list = list ? JSON.parse(list) || []; // if there is a list already
list.forEach(({ name, title }) => wrapper(name, title)); // show
document.getElementById("form").addEventListener("submit", function(e) {
e.preventDefault(); // stop submission
const name = document.getElementById("name").value;
const title = document.getElementById("title").value;
const wrapper = wrapper(name, title);
list.push({ name, title })
localStorage.setItem("list", JSON.stringify(list));
});
function wrapper(name, title) {
const header = document.createElement("h2");
header.textContent = name;
const p = document.createElement("p");
p.textContentt = title;
const div = document.createElement("div");
div.classList.add("list");
div.append(header)
div.append(p)
outList.append(div);
}
})
<form action="#" id="form">
<div class="form-section">
<label for="name">Input Name</label>
<input type="text" id="name">
</div>
<div class="form-section">
<label for="title">Input Name</label>
<input type="text" id="title">
</div>
<button class="submit-btn">Submit</button>
</form>
<div id="container"></div>
I am validating a login form and for each error with the form validation (e.g. incorrect username or email format), I want to display an unordered list containing the errors. I know how to validate the input etc. but I can't figure out how to add in an unordered list in my if statements. I know these if statements may be inefficient for validation and incorporating an unordered list will recreate an unordered list in each if statement. but I am required to learn JavaScript in 3 weeks. Here is my HTML code:
let fullName = document.getElementById("fullName");
let formErrors = document.getElementById("formErrors");
let email = document.getElementById("email");
let emailRegex = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,5}$/
let password = document.getElementById("password");
let passwordConfirm = document.getElementById("passwordConfirm");
let submitButton = document.getElementById("submit");
function checkForm() {
// TODO: Perform input validation
if (fullName.value < 1) {
formErrors.style.display = "block";
formErrors.innerHTML = "Missing full name";
};
if (email != emailRegex) {
formErrors.style.display = "block";
formErrors.innerHTML = "Missing email";
}
if (password.value < 10 || password.value > 20) {
formErrors.style.display = "block";
formErrors.innerHTML = "Password must be between 10 and 20 characters."
}
}
document.getElementById("submit").addEventListener("click", function(event) {
checkForm();
// Prevent default form action. DO NOT REMOVE THIS LINE
event.preventDefault();
});
<h1>User Registration</h1>
<form>
<label for="fullName">Full Name</label> <br>
<input type="text" id="fullName" class="defaulx"> <br>
<label for="email">Email</label> <br>
<input type="email" id="email" class="defaulx"> <br>
<label for="password">Password</label> <br>
<input type="password" id="password" class="defaulx"> <br>
<label for="passwordConfirm">Confirm Password</label> <br>
<input type="password" id="passwordConfirm" class="defaulx"> <br>
<input type="submit" id="submit" value="Register">
</form>
<div id="formErrors" style="display: none;"></div>
</div>
As you know how to validate and do the conditions, I am just adding only a fragment to support your code. Hopes this will help you to create a list of errors.
function checkForm() {
// TODO: Perform input validation
var ul = document.createElement('UL');
if (true) {
var li = document.createElement('LI');
li.innerHTML = "Missing full name";
ul.appendChild(li);
};
if (true) {
var li = document.createElement('LI');
li.innerHTML = "Missing email";
ul.appendChild(li);
}
if (true) {
var li = document.createElement('LI');
li.innerHTML = "Password must be between 10 and 20 characters."
ul.appendChild(li);
}
document.getElementById('formErrors').appendChild(ul);
}
checkForm();
<div id="formErrors"></div>
What the code does is
var ul = document.createElement('UL');
this will create a <ul></ul> element.
on each if
var li = document.createElement('LI');
this will create a <li></li> element
li.innerHTML = "Missing email";
this will set the html value to it.
ul.appendChild(li);
this will append the li to the ul providing <ul><li></li></ul>
Here's my approach:
let fullName = document.getElementById("fullName");
let formErrors = document.getElementById("formErrors");
let email = document.getElementById("email");
let emailRegex = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,5}$/
let password = document.getElementById("password");
let passwordConfirm = document.getElementById("passwordConfirm");
let submitButton = document.getElementById("submit");
function checkForm() {
// TODO: Perform input validation
const errors = []
if (fullName.value < 1) {
errors.push("Missing full name");
}
if (!emailRegex.test(email.value)){ // note this change
errors.push("Missing email");
}
if (password.value < 10 || password.value > 20) {
errors.push("Password must be between 10 and 20 characters.");
}
let ul = document.createElement("ul");
errors.forEach(error => {
let li = document.createElement("li");
li.innerHTML = error;
ul.appendChild(li);
});
formErrors.innerHTML = ""; // clear what had been displayed
formErrors.appendChild(ul);
}
document.getElementById("submit").addEventListener("click", function (event) {
checkForm();
// Prevent default form action. DO NOT REMOVE THIS LINE
event.preventDefault();
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>User Registration</title>
<link href="style.css" rel="stylesheet">
<script src="register.js" defer></script>
</head>
<body>
<h1>User Registration</h1>
<form>
<label for="fullName">Full Name</label> <br>
<input type="text" id="fullName" class="defaulx"> <br>
<label for="email">Email</label> <br>
<input type="email" id="email" class="defaulx"> <br>
<label for="password">Password</label> <br>
<input type="password" id="password" class="defaulx"> <br>
<label for="passwordConfirm">Confirm Password</label> <br>
<input type="password" id="passwordConfirm" class="defaulx"> <br>
<input type="submit" id="submit" value="Register">
</form>
<div id="formErrors"></div>
</div>
</body>
</html>
I have a text input where user have to enter their surname and I want that surname as they enter it to appear below in a dropdown, using HTML and Javascript. This is my code so far but it does not work:
<form id= 'surnameReg'>
<label for='surname'>Surname:</label>
<input type='text' id="surname">
</form>
<form id='chooseSur'>
<label for="who">Who:</label>
<select id="who">
</select>
</form>
And my JS:
function drop() {
var surnArr=[];
var select = document.getElementById("who");
for(var i = 0; i <surnArr.length; i++) {
var sur= surnArr[i];
var op = document.createElement("option");
op.textContent = sur;
op.value = sur;
select.appendChild(op);
}
}
You can set an event listener on the first form on submit and then create and append the option as follows:
document.getElementById("surnameReg").addEventListener("submit",function(e){
e.preventDefault();
let surname = document.getElementById("surname").value;
if(surname){
var select = document.getElementById("who");
var op = document.createElement("option");
op.textContent = surname;
op.value = surname;
select.appendChild(op);
}
});
<form id= 'surnameReg' >
<label for='surname'>Surname:</label>
<input type='text' id="surname" >
</form>
<form id='chooseSur' >
<label for="who">Who:</label>
<select id="who">
</select>
</form>