user gives full names ages amka(html javascript) - javascript

function createPerson() {
var fullname = document.getElementById('inputValueFullname').value;
var age = document.getElementById('inputValueAge').value;
var amka = document.getElementById('inputValueAmka').value;
function person(fullname, age, amka) {
this.fullname = fullname;
this.age = age;
this.amka = amka;
}
var NewPerson = new person(name, age, amka);
console.log(NewPerson);
}
<label>Fullname: <input type="text" id="inputValueFullname"></label>
<label>Age:<input type="text" id="inputValueAge"></label>
<label>Amka:<input type="text" id="inputValueAmka"></label>
<button id="btn" onclick="createPerson();">Add</button>
I want someone to help me with 2 problems
the user gives full name age and amka and I want them all to appear below in a list as in the photo below
I have a code that I tried separately but I do not know how to put them together
i want when someone give age<18 to stop to take more inputs
to use for this for or if and how to do it
function publishToTable() {
const fullname = document.getElementById('fullname').value;
const age = document.getElementById('age').value;
const amka = document.getElementById('amka').value;
const error = document.getElementById('error');
if (fullname && age && amka) {
const tableElement = document.getElementById('table');
const trElement = document.createElement('tr');
const tbodyElement = document.createElement('tbody');
const fullnameEle = document.createElement('td');
const ageEle = document.createElement('td');
const amkaEle = document.createElement('td');
fullnameEle.innerHTML = fullname;
ageEle.innerHTML = age;
amkaEle.innerHTML = amka;
trElement.appendChild(fullnameEle);
trElement.appendChild(ageEle);
trElement.appendChild(amkaEle);
tbodyElement.appendChild(trElement);
tableElement.appendChild(tbodyElement);
}
}
<div class="complete">
<div class="form">
<label>Fullname: <input id="fullname" type="text"></label>
<label>Age: <input id="age" type="text"></label>
<label>AMKA: <input id="amka" type="text"></label>
<span id="error"></span>
<button onclick="publishToTable()">Submit</button>
</div>
<div id="tables">
<table id="table">
<thead>
<tr>
<th>Name/Surname</th>
<th>Age</th>
<th>AMKA</th><br><br><br><br><br>
</tr>
</thead>
</table>
</div>
</div>

I suggest you use an array.
I have made some other recommended changes, such as using an eventListener and an Array.map
const person = (fullname, age, amka) => ({ fullname, age, amka }); // return an object, shorthand for { "fullname": fullname ....
const persons = [];
const error = document.getElementById('error');
const tableElement = document.getElementById('table');
const fullnameField = document.getElementById('fullname')
const ageField = document.getElementById('age')
const amkaField = document.getElementById('amka')
const publishToTable = () => tableElement.innerHTML = persons
.map(({ fullname, age, amka }) => `<tr><td>${fullname}</td><td>${age}</td><td>${amka}</td></tr>`).join("");
document.getElementById("save").addEventListener("click", e => {
let fullname = fullnameField.value;
let age = +ageField.value; // cast to number
let amka = amkaField.value;
if (isNaN(age) || age < 18) {
ageField.focus();
error.innerHTML = "Incorrect age (18 minimum)"
return; // stop
}
error.innerHTML = "";
persons.push(person(fullname, age, amka));
fullnameField.value = ageField.value = amkaField.value = ""; // reset
fullnameField.focus()
publishToTable();
})
<div class="complete">
<div class="form">
<label>Fullname: <input id="fullname" type="text"></label>
<label>Age: <input id="age" type="text"></label>
<label>AMKA: <input id="amka" type="text"></label>
<span id="error"></span>
<button type="button" id="save">Save</button>
</div>
<div id="tables">
<table>
<thead>
<tr>
<th>Name/Surname</th>
<th>Age</th>
<th>AMKA</th><br><br><br><br><br>
</tr>
</thead>
<tbody id="table">
</table>
</table>
</div>
</div>

Related

need to append user data to array

my original question got answered but I realize that every time I try to push user data in the arrays it wouldn't allow me to do is there any another to append data to arrays or is the push method the only way. or should i create a new array................................................................
"use strict"
const names = ["Ben", "Joel", "Judy", "Anne"];
const scores = [88, 98, 77, 88];
const $ = selector => document.querySelector(selector);
const addScore = () => {
// get user entries
const name = $("#name").value;
const score = parseInt($("#score").value);
let isValid = true;
// check entries for validity
if (name == "") {
$("#name").nextElementSibling.textContent = "This field is required.";
isValid = false;
} else {
$("#name").nextElementSibling.textContent = "";
}
if (isNaN(score) || score < 0 || score > 100) {
$("#score").nextElementSibling.textContent = "You must enter a valid score.";
isValid = false;
} else {
$("#score").nextElementSibling.textContent = "";
}
if (isValid) {
names.push("#name");
scores.push("#score");
names[names.length] = name;
scores[scores.length] = score;
$("#name").value = "";
$("#score").value = "";
}
$("#name").focus();
};
// display scores
const displayScores = () => {
for (let i = 0; i < names.length; i++) {
document.getElementById("scores_display").textContent += names[i] + " = " +
scores[i] +
"\n";
}
};
document.addEventListener("DOMContentLoaded", () => {
$("#add").addEventListener("click", addScore);
$("#display_scores").addEventListener("click", displayScores())
$("#name").focus();
});
<main>
<h1>Use a Test Score array</h1>
<div>
<label for="name">Name:</label>
<input type="text" id="name">
<span></span>
</div>
<div>
<label for="score">Score:</label>
<input type="text" id="score">
<span></span>
</div>
<div>
<label> </label>
<input type="button" id="add" value="Add to Array">
<input type="button" id="display_scores" value="Display Scores">
</div>
<div>
<textarea id="scores_display"></textarea>
</div>
</main>
All my previous notes were incorrect. Your adhoc $ const threw me off! My apologies.
The issue was you weren't calling displayScores() after updating the array. Plus, I added a line to that function to clear the existing text before looping through your data.
"use strict"
const names = ["Ben", "Joel", "Judy", "Anne"];
const scores = [88, 98, 77, 88];
const $ = selector => document.querySelector(selector);
const addScore = () => {
// get user entries
const name = $("#name").value;
const score = parseInt($("#score").value);
let isValid = true;
// check entries for validity
if (name == "") {
$("#name").nextElementSibling.textContent = "This field is required.";
isValid = false;
} else {
$("#name").nextElementSibling.textContent = "";
}
if (isNaN(score) || score < 0 || score > 100) {
$("#score").nextElementSibling.textContent = "You must enter a valid score.";
isValid = false;
} else {
$("#score").nextElementSibling.textContent = "";
}
if (isValid) {
names.push("#name");
scores.push("#score");
names[names.length] = name;
scores[scores.length] = score;
$("#name").value = "";
$("#score").value = "";
// add to the textarea
displayScores()
}
$("#name").focus();
};
// display scores
const displayScores = () => {
document.getElementById("scores_display").textContent = "";
for (let i = 0; i < names.length; i++) {
document.getElementById("scores_display").textContent += names[i] + " = " +
scores[i] +
"\n";
}
};
document.addEventListener("DOMContentLoaded", () => {
$("#add").addEventListener("click", addScore);
$("#display_scores").addEventListener("click", displayScores())
$("#name").focus();
});
<main>
<h1>Use a Test Score array</h1>
<div>
<label for="name">Name:</label>
<input type="text" id="name">
<span></span>
</div>
<div>
<label for="score">Score:</label>
<input type="text" id="score">
<span></span>
</div>
<div>
<label> </label>
<input type="button" id="add" value="Add to Array">
<input type="button" id="display_scores" value="Display Scores">
</div>
<div>
<textarea rows="6" id="scores_display"></textarea>
</div>
</main>

Display data in a table from localStorage without repeating

I am making a shopping list in my web page where I add the items which I store in localStorage.The items are displayed in a table.The problem is that for each new item added it is showing also the data previously stored again.
My html is:
<form class="market">
<label>Nume produs</label>
<input type="text" id="np">
<label>Cantitate</label>
<input type="text" id="cp">
<input type="button" onclick="addItem();" id="adauga" value="Adaugă" />
</form>
<table>
<tbody id="shopping">
<tr>
<th>Nr.</th>
<th>Name</th>
<th>Quantity</th>
</tr>
And this is the function called on every button click
class Produs{
constructor(id, nume, cantitate){
this.id = id;
this.nume = nume;
this.cantitate = cantitate;
}
}
function addItem(){
let nume = document.getElementById("np").value;
let cantitate = document.getElementById("cp").value;
let produse = localStorage.getItem('produse');
if(produse == null){
produse = [];
}
else{
produse = JSON.parse(produse);
}
produse = produse.map((p) => {
return new Produs(p.id, p.nume, p.cantitate);
});
let lastId = localStorage.getItem('lastId');
if(lastId == null)
{
lastId=1;
}
else{
lastId = JSON.parse(lastId);
}
let id = lastId;
produse.push(new Produs(id, nume, cantitate));
localStorage.setItem('produse',JSON.stringify(produse));
localStorage.setItem('lastId',JSON.stringify(lastId+1));
var jsonData = JSON.parse(localStorage.getItem('produse'));
console.log(jsonData);
for(var i=0; i<jsonData.length; i++)
{
document.getElementById("shopping").innerHTML +="<tr><td>"+jsonData[i].id +"</td><td>" + jsonData[i].nume +"</td><td>"+jsonData[i].cantitate+"</td></tr>";
}
}

Loading default text string to a table by javascript

I’ve made a form where I want the users to be able to add books (title, author, isbn).
<fieldset>
<legend>Bokdata</legend>
<label for="txtBookTitle">Tittel</label>
<input id="txtBookTitle" type="text" value="">
<label for="txtBookAuthor">Forfatter</label>
<input id="txtBookAuthor" type="text" value="">
<label for="txtBookISBN">ISBN</label>
<input id="txtBookISBN" type="text" value="">
<p>
<button onclick="addBookClick()">Legg til</button>
</p>
</fieldset>
The books will appear in this table:
<table border="2">
<thead>
<tr>
<th colspan="3">
Min bokliste
</th>
</tr>
<tr>
<th>Tittel</th>
<th>Forfatter</th>
<th>ISBN</th>
</tr>
</thead>
<tbody id="tblBodyList">
</tbody>
<tfoot id="tblSummary">
</tfoot>
</table>
Adding books by using the input-fields is done by this function:
function addBookClick(){
//Input fra skjemaet
var txtBookTitle = document.getElementById("txtBookTitle").value;
var txtBookAuthor = document.getElementById("txtBookAuthor").value;
var txtBookISBN = document.getElementById("txtBookISBN").value;
// Lag html-tabell
// 0 = tabell 1
var table = document.getElementsByTagName("table")[0];
// Legg til ny rad nederst i tabellen. (0) = øverste rad i tabellen.
var newRow = table.insertRow(table.rows.length);
// Legg til celler i tabellen
var cel1 = newRow.insertCell(0);
var cel2 = newRow.insertCell(1);
var cel3 = newRow.insertCell(2);
// Legg til values i cellene
cel1.innerHTML = txtBookTitle;
cel2.innerHTML = txtBookAuthor;
cel3.innerHTML = txtBookISBN;
}
I’m trying to insert some text into a table without html, but by javascript instead. The easiest would of course be to write the text in the table, but this is a school assignment, and I’m not allowed to do that. Getting help is allowed. I hope I’m close to something, but I could really use some advice. I’ve tried the last two days to get a grip on this:
var txtBookTitle = document.getElementById("txtBookTitle");
var txtBookAuthor = document.getElementById("txtBookAuthor");
var txtBookISBN = document.getElementById("txtBookISBN");
var tblBodyList = document.getElementById("tblBodyList");
var books = [];
var defaultBooks =
"Judo Unleashed,Neil Ohlenkamp,0-07-147534-6\n"+
"Kodokan Judo,Jigoro Kano,0-87011-681-9\n"+
"Olympic Judo,Neil Adams,0-7207-1735-3";
var book = {
title: "txtBookTitle",
author: "txtBookAuthor",
ISBN: "txtBookISBN"
};
function createBook(title, author, ISBN){
var Book = {};
Book.title = title;
Book.author = author;
Book.ISBN = ISBN;
books.push(Book);
return Book
}
var judo = "";
var kodokan = "";
var olympic = "";
function loadDefaultBooks(){
judo = createBook("Judo Unleashed", "Neil Ohlenkamp", "0-07-147534-6");
kodokan = createBook("Kodokan Judo", "Jigoro Kano", "0-87011-681-9");
olympic = createBook("Olympic Judo" , "Neil Adams" , "0-7207-1735-3");
listBooks();
}
In your case you are not calling loadDefaultBooks. Also the function createBook is not making any sense. You can use the same function addBookClick and pass argument.
This line var txtBookTitle = a || document.getElementById("txtBookTitle").value; when a has a value consider that value, other on click of button a will be undefined. In that case consider the value from the input text
function addBookClick(a, b, c) {
//Input fra skjemaet
var txtBookTitle = a || document.getElementById("txtBookTitle").value;
var txtBookAuthor = b || document.getElementById("txtBookAuthor").value;
var txtBookISBN = c || document.getElementById("txtBookISBN").value;
// Lag html-tabell
// 0 = tabell 1
var table = document.getElementsByTagName("table")[0];
// Legg til ny rad nederst i tabellen. (0) = øverste rad i tabellen.
var newRow = table.insertRow(table.rows.length);
// Legg til celler i tabellen
var cel1 = newRow.insertCell(0);
var cel2 = newRow.insertCell(1);
var cel3 = newRow.insertCell(2);
// Legg til values i cellene
cel1.innerHTML = txtBookTitle;
cel2.innerHTML = txtBookAuthor;
cel3.innerHTML = txtBookISBN;
}
function loadDefaultBooks() {
addBookClick("Judo Unleashed", "Neil Ohlenkamp", "0-07-147534-6");
addBookClick("Kodokan Judo", "Jigoro Kano", "0-87011-681-9");
addBookClick("Olympic Judo", "Neil Adams", "0-7207-1735-3");
}
loadDefaultBooks()
<fieldset>
<legend>Bokdata</legend>
<label for="txtBookTitle">Tittel</label>
<input id="txtBookTitle" type="text" value="">
<label for="txtBookAuthor">Forfatter</label>
<input id="txtBookAuthor" type="text" value="">
<label for="txtBookISBN">ISBN</label>
<input id="txtBookISBN" type="text" value="">
<p>
<button onclick="addBookClick()">Legg til</button>
</p>
</fieldset>
<table border="2">
<thead>
<tr>
<th colspan="3">
Min bokliste
</th>
</tr>
<tr>
<th>Tittel</th>
<th>Forfatter</th>
<th>ISBN</th>
</tr>
</thead>
<tbody id="tblBodyList">
</tbody>
<tfoot id="tblSummary">
</tfoot>
</table>

Why does not work method of deleting items by name?

The method of removing products by their name does not work. I'm trying to delete using buttDelete.addEventListener but the deletion does not happen.
The logic of the deleteProductByName method is that when the name of product is received from input nameDelete it is checked the same products in shop.products array, then when the button delete is press (buttDelete), the product is deleted from the array and correspondingly from the table too, if the field is empty, then output alert that you need to fill out the field.
Help please fix that
//Product Creation Class
class Product {
constructor(name, count, price) {
this.name = name;
this.count = count;
this.price = price;
}
}
// Сlass where products are recorded
class Shop {
constructor() {
this.products = [];
}
//method for adding a product
addProduct(newProduct) {
this.products.push(newProduct);
}
//method for remove product by name
deleteProductByName(productName) {
let i = this.products.length;
while (i--) {
if (productName === this.products[i].name) {
this.products.splice(i, 1);
}
}
}
// get total price by all products
get totalProductsPrice() {
return this.products.map(product => product.price).reduce((p, c) => p + c);
}
// method to draw the table with product property (
// name, count, price)
show() {
const rows = document.querySelectorAll("#shop .data");
for (let i = rows.length - 1; i >= 0; i--) {
const e = rows.item(i);
e.parentNode.removeChild(e);
}
const table = document.getElementById("shop");
for (let i = 0; i < this.products.length; i++) {
//create table
table.innerHTML += `<tbody><tr class="data"><td>${this.products[i].name}</td>
<td>${this.products[i].price}</td>
<td>${this.products[i].count}</td></tr></tbody>`;
}
//show total price by all products
table.innerHTML += `<tfoot><tr id="total-price"><td colspan="3">Total price:
${shop.totalProductsPrice}</td></tr></tfoot>`;
}
}
// add new product by click
const formAdd = document.forms[0];
const inputsAdd = formAdd.elements;
const buttAdd = formAdd.elements[3];
buttAdd.addEventListener('click', (e) => {
e.preventDefault();
shop.addProduct(new Product(inputsAdd[0].value, parseInt(inputsAdd[2].value),
parseInt(inputsAdd[1].value)));
shop.show();
}, false);
// delete product by name after click
const formDelete = document.forms[1];
const nameDelete = formDelete.elements[0];
const buttDelete = formDelete.elements[1];
buttDelete.addEventListener('click', (e) => {
e.preventDefault();
shop.deleteProductByName(nameDelete.value);
shop.show();
}, false);
let shop = new Shop();
shop.addProduct(new Product("product 1", 1, 2000));
shop.show();
<div class="Shop">
<div class="add-product">
<h1>Add product</h1>
<form id="addForm">
<label for="name" >Name of product</label>
<input type="text" id="name" class="input-product">
<label for="price">Price of product</label>
<input type="text" id="price" class="input-product">
<label for="count">Count of product</label>
<input type="text" id="count" class="input-product">
<button id="add">Add</button>
</form>
</div>
<div class="product-table">
<h2>Products</h2>
<form id="delete-form">
<label for="name-delete">Delete product by name</label>
<input type="text" id="name-delete" class="input-delete">
<button id="delete" type="button">Delete</button>
</form>
<table id="shop">
<caption>Products that are available in the store</caption>
<tr>
<th>Name:</th>
<th id="filter">Price:</th>
<th>Count:</th>
</tr>
</table>
</div>
</div>
Then I would use a console.log() or a debugger on
//method for remove product by name
deleteProductByName(productName) {
let i = this.products.length;
while (i--) {
console.log("productName " + productName + "this.products[i].name" + this.products[i].name);
if (productName === this.products[i].name) {
this.products.splice(i, 1);
}
}
}
to see if you comparing the same names. To make sure your if statement is working as expected.

How to transfer a value from inputs to array?

I want to transfer the value from three inputs: "name", "counter" and "price" to the array "products" that I then display in the table. But when I add them using the buttAdd.addEventListener handler, the new elements are not displayed in the table Help fix this
//Product Creation Class
class Product {
constructor(name, count, price) {
this.name = name;
this.count = count;
this.price = price;
}
}
// Сlass where products are recorded
class Shop {
constructor(products) {
this.products = [];
}
//method for adding a product
addProduct(newProduct) {
this.products.push(newProduct);
}
show() {
const rows = document.querySelectorAll("#shop .data");
for (let i = rows.length - 1; i >= 0; i--) {
const e = rows.item(i);
e.parentNode.removeChild(e);
}
const table = document.getElementById("shop");
for (let i = 0; i < this.products.length; i++) {
//create table
table.innerHTML += `<tr class="data"><td>${this.products[i].name}</td>
<td>${this.products[i].price}</td>
<td>${this.products[i].count}</td></tr>`;
}
}
}
const formAdd = document.forms[0];
const inputsAdd = formAdd.elements;
const buttAdd = formAdd.elements[3];
buttAdd.addEventListener('click', (e) => {
for (let i = 0; i <= 3; i++) {
shop.addProduct(inputsAdd[i].value);
}
shop.show();
}, false);
let shop = new Shop();
shop.addProduct(new Product("product 1", 1, 2000));
shop.show();
<form id="addForm">
<label for="name" >Name of product</label>
<input type="text" id="name" class="input-product">
<label for="price">Price of product</label>
<input type="text" id="price" class="input-product">
<label for="count">Count of product</label>
<input type="text" id="count" class="input-product">
<button id="add">Add</button>
</form>
<table id="shop">
<caption>Products that are available in the store</caption>
<tr>
<th>Name:</th>
<th id="filter">Price:</th>
<th>Count:</th>
</tr>
</table>
Below are the errors in your code.
Your for loop inside buttAdd.addEventListener is not correct.condition <=3 will iterate 4 time while input fields are only 3.
shop.addProduct(inputsAdd[i].value); is wrong because addProduct method of shop class required Product class object so you need to create new Product class object and set the values of input through constructor.
This is the correct way:
shop.addProduct(new Product(inputsAdd[0].value,inputsAdd[1].value,inputsAdd[2].value));
Here is the running snippet
//Product Creation Class
class Product {
constructor(name, count, price) {
this.name = name;
this.count = count;
this.price = price;
}
}
// Сlass where products are recorded
class Shop {
constructor(products) {
this.products = [];
}
//method for adding a product
addProduct(newProduct) {
this.products.push(newProduct);
}
show() {
const rows = document.querySelectorAll("#shop .data");
for (let i = rows.length - 1; i >= 0; i--) {
const e = rows.item(i);
e.parentNode.removeChild(e);
}
const table = document.getElementById("shop");
for (let i = 0; i < this.products.length; i++) {
//create table
table.innerHTML += `<tr class="data"><td>${this.products[i].name}</td>
<td>${this.products[i].price}</td>
<td>${this.products[i].count}</td></tr>`;
}
}
}
const formAdd = document.forms[0];
const inputsAdd = formAdd.elements;
const buttAdd = formAdd.elements[3];
//console.log(buttAdd);
buttAdd.addEventListener('click', (e) => {
e.preventDefault();
shop.addProduct(new Product(inputsAdd[0].value,parseInt(inputsAdd[1].value),inputsAdd[2].value));
shop.show();
}, false);
let shop = new Shop();
shop.addProduct(new Product("product 1", 1, 2000));
shop.show();
<form id="addForm">
<label for="name" >Name of product</label>
<input type="text" id="name" class="input-product">
<label for="price">Price of product</label>
<input type="text" id="price" class="input-product">
<label for="count">Count of product</label>
<input type="text" id="count" class="input-product">
<button id="add">Add</button>
</form>
<table id="shop">
<caption>Products that are available in the store</caption>
<tr>
<th>Name:</th>
<th id="filter">Price:</th>
<th>Count:</th>
</tr>
</table>
Your addProduct() method takes in a Product object as input, but in click listener you are passing form field input values without forming a object
//Product Creation Class
class Product {
constructor(name, count, price) {
this.name = name;
this.count = count;
this.price = price;
}
}
// Сlass where products are recorded
class Shop {
constructor(products) {
this.products = [];
}
//method for adding a product
addProduct(newProduct) {
this.products.push(newProduct);
}
show() {
const rows = document.querySelectorAll("#shop .data");
for (let i = rows.length - 1; i >= 0; i--) {
const e = rows.item(i);
e.parentNode.removeChild(e);
}
const table = document.getElementById("shop");
for (let i = 0; i < this.products.length; i++) {
//create table
table.innerHTML += `<tr class="data"><td>${this.products[i].name}</td>
<td>${this.products[i].price}</td>
<td>${this.products[i].count}</td></tr>`;
}
}
}
const formAdd = document.forms[0];
const inputsAdd = formAdd.elements;
const buttAdd = formAdd.elements[3];
buttAdd.addEventListener('click', (e) => {
e.preventDefault();
let tempProduct = new
Product(inputsAdd[0].value,parseInt(inputsAdd[1].value),parseInt(inputsAdd[2].value));
shop.addProduct(tempProduct);
shop.show();
}, false);
let shop = new Shop();
shop.addProduct(new Product("product 1", 1, 2000));
shop.show();
<form id="addForm">
<label for="name" >Name of product</label>
<input type="text" id="name" class="input-product">
<label for="price">Price of product</label>
<input type="text" id="price" class="input-product">
<label for="count">Count of product</label>
<input type="text" id="count" class="input-product">
<button id="add">Add</button>
</form>
<table id="shop">
<caption>Products that are available in the store</caption>
<tr>
<th>Name:</th>
<th id="filter">Price:</th>
<th>Count:</th>
</tr>
</table>

Categories