I have an html form with item and amount entries and I want the values in them to be stored in local storage and xampp, I have succeeded in submiting to localstorage however the form submits nothing in xampp in a column for item and 0 in the column of amount
here is my html file
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>ICT specialists</title>
<meta name="description" content="" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="app.css" />
<link rel="shortcut icon" href="ICT_Logo-01.png">
</head>
<body>
<h2>Daily transactions at ICT specialists</h2>
<div class="container">
<h4>Your balance</h4>
<h1 id="balance"></h1>
<div class="inc-exp-container">
<div>
<h4>income</h4>
<p id="money-plus" class="money plus"></p>
</div>
<div>
<h4>expense</h4>
<p id="money-minus" class="money minus"></p>
</div>
</div>
<h3>History</h3>
<div class="shows">
<ion-icon name="menu-outline" id="showLi"></ion-icon>
<ion-icon name="close-outline" id="hideLi"></ion-icon>
</div>
<ul id="list" class="list"></ul>
<h3>add new transation</h3>
<form action="sales.php" method="post" id="form">
<div class="form-control">
<label for="">date</label>
<input type="text" id="date" name="date">
</div>
<div class="form-control">
<label for="text">item</label>
<input type="text" id="text" name="item" placeholder="please enter the item..." autocomplete="off" />
</div>
<div class="form-control">
<label for="amount">amount <br />(negative=expense, positive=income)</label>
<input type="number" id="amount" name="amount" placeholder="please enter the amount..." autocomplete="off" />
</div>
<button class="btn" type="submit">Add transation</button>
</form>
</div>
<div class="footer">
<div class="footerTxt">copyright © <span id="dated">2022</span</div>
<div class="footerRyt">
ict specialists | sydotech
</div>
</div>
<style>
.footer{
display: flex;
justify-content: space-evenly;
width: 100%;
bottom: 0;
background: deepskyblue !important;
padding: 10px;
position: fixed;
}
.footer .footerTxt{
font-size: 1.2rem;
text-transform: capitalize;
font-weight: 500;
}
.footer .footerRyt a{
text-decoration: none;
font-size: 1.4rem;
color: #fff !important;
}
</style>
<ion-icon name="arrow-up-outline" id="icons"></ion-icon>
<script src="sales.js"></script>
<script type="module" src="https://unpkg.com/ionicons#5.5.2/dist/ionicons/ionicons.esm.js">
</script>
<script nomodule src="https://unpkg.com/ionicons#5.5.2/dist/ionicons/ionicons.js"></script>
</body>
</html>
here is my php
<?php
$pdo = new PDO('mysql:host=localhost;port=3306;dbname=sales','root','');
$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
if($_SERVER['REQUEST_METHOD']==='POST'){
$item = $_POST['item'];
$amount = $_POST['amount'];
$statement = $pdo->prepare("insert into transaction
(item,amount)
values (:item,:amount)");
$statement->bindValue(':item', $item );
$statement->bindValue(':amount', $amount );
$statement->execute();
header('Location: sales.html');
}
here is my javascript file
const balance = document.getElementById("balance");
const money_plus = document.getElementById("money-plus");
const list = document.getElementById("list");
const form = document.getElementById("form");
const text = document.getElementById("text");
const amount = document.getElementById("amount");
const money_minus = document.getElementById("money-minus");
let showLi = document.getElementById("showLi");
let hideLi = document.getElementById('hideLi');
const localStorageTransations = JSON.parse(localStorage.getItem("transations"));
let transations =
localStorage.getItem("transations") !== null ? localStorageTransations : [];
//add transation
function addTransation() {
// e.preventDefault();
if (text.value.trim() === "" || amount.value.trim() === "") {
text.placeholder = "PLEASE SOME TEXT";
text.style.backgroundColor = "#ccc";
text.style.fontWeight = 'bold';
amount.placeholder = "ENTER AMOUNT";
amount.style.backgroundColor = "#ccc";
amount.style.fontWeight = 'bold';
} else {
const transation = {
id: genenrateID(),
text: text.value,
amount: +amount.value,
};
transations.push(transation);
addTransationDOM(transation);
updateValues();
updateLocalStorage();
text.value = "";
amount.value = "";
}
}
//generate id
function genenrateID() {
return Math.floor(Math.random() * 100000000);
}
//add transations to dom list
function addTransationDOM(transation) {
//get sign
const sign = transation.amount < 0 ? "-" : "+";
const item = document.createElement("li");
//add class based on value
item.classList.add(transation.amount < 0 ? "minus" : "plus");
item.innerHTML = `${transation.text} <span>${sign}${Math.abs(transation.amount)}</span>
<button class="delete-btn" onclick="removeTransation(${transation.id})">x</button>`;
list.appendChild(item);
item.style.display="none";
hideLi.addEventListener('click',()=>{
item.style.display = 'none';
hideLi.style.display = "none";
showLi.style.display = "block";
});
showLi.addEventListener('click',()=>{
item.style.display = 'block';
hideLi.style.display = "block";
showLi.style.display = "none";
})
}
// ********hide list******
// ********hide list end******
//update the balance
function updateValues() {
const amounts = transations.map((transation) => transation.amount);
const total = amounts.reduce((acc, item) => (acc += item), 0).toFixed(0);
const income = amounts
.filter((item) => item > 0)
.reduce((acc, item) => (acc += item), 0)
.toFixed(0);
const expense = (
amounts.filter((item) => item < 0).reduce((acc, item) => (acc += item), 0) * -1).toFixed(0);
balance.innerText = `UgShs: ${total}`;
money_plus.innerText = `UgShs: ${income}`;
money_minus.innerText = `UgShs: ${expense}`;
}
//remove
function removeTransation(id) {
transations = transations.filter((transation) => transation.id !== id);
updateLocalStorage();
init();
}
//updatelocal storage
function updateLocalStorage() {
localStorage.setItem("transations", JSON.stringify(transations));
}
function init() {
list.innerHTML = "";
transations.forEach(addTransationDOM);
updateValues();
}
init();
form.addEventListener("submit", addTransation);
// *********date calculation********
let date =document.getElementById('date');
date.value = new Date().toDateString();
// *********ionicons*******88
let icon = document.getElementById('icons');
window.onscroll = ()=>{
if(window.scrollY >=100){
icon.style.display = 'block';
icon.style.position = 'fixed';
}else{
icon.style.display = 'none';
}
}
icon.addEventListener('click',()=>{
window.scrollTo({top:0, behavior:"smooth"})
})
let span11 = document.getElementById('dated');
span11.innerHTML = new Date().getFullYear();
Related
I have the following function to determine the status of whether a book was read or not in my project each time a new book is added to the library. The issue I am running into is that every time I add a new book, all the books "Status" are updated to the status of the new book.
PROBLEM CODE
const titleInput = document.querySelector('#title');
const authorInput = document.querySelector('#author');
const pagesInput = document.querySelector('#pages');
const genreInput = document.querySelector('#genre');
let readInput;
function readStatus() {
const readRadioBtn = document.querySelector('input[name="read"]');
if (readRadioBtn.checked) {
return 'read';
}
return 'unread';
}
// function to add book to myLibrary array//
function addBook() {
const newBook = new Book(
titleInput.value,
authorInput.value,
pagesInput.value,
genreInput.value,
readInput = readStatus()
);
myLibrary.push(newBook);
}
I have tried to declare the readInput variable inside addBook() before newBook, but then a new book card does not get added at all. The form gets reset upon submission as well. I am attaching my full HTML and JavaScript code below for more clarity on what I am trying to get done. I apologize if it is unorganized as I am still new to coding. I also really appreciate any advice and tips on how I can structure and write my code better.
CODE
// OPENING AND CLOSING MODAL//
const addBookBtn = document.querySelector('.add');
const closeModalBtn = document.querySelector('.close-btn');
const overlay = document.querySelector('.overlay');
const modal = document.querySelector('.modal');
function openModal() {
modal.classList.add('active');
overlay.classList.add('active');
}
function closeModal() {
modal.classList.remove('active');
overlay.classList.remove('active');
}
addBookBtn.addEventListener('click', () => {
openModal();
});
closeModalBtn.addEventListener('click', () => {
closeModal();
});
// CREATING NEW BOOK CARDS//
const myLibrary = [];
// constructor function//
function Book(title, author, pages, genre, read) {
(this.title = title),
(this.author = author),
(this.pages = pages),
(this.genre = genre),
(this.read = read);
}
// need to fix//
function readStatus() {
if (document.querySelector('input[name="read"]').value === 'yes') {
return 'read';
}
if (document.querySelector('input[name="read"]').value === 'no') {
return 'unread';
}
}
const titleInput = document.querySelector('#title');
const authorInput = document.querySelector('#author');
const pagesInput = document.querySelector('#pages');
const genreInput = document.querySelector('#genre');
let readInput;
// function to add book to myLibrary array//
function addBook() {
readInput = readStatus();
const newBook = new Book(
titleInput.value,
authorInput.value,
pagesInput.value,
genreInput.value,
readInput
);
myLibrary.push(newBook);
}
// creates new book card elements in DOM//
function createNewCard(book) {
const cardContainer = document.querySelector('.card-cont');
const cards = document.createElement('div');
cards.classList.add('book-card');
const title = document.createElement('p');
title.innerText = book.title;
cards.appendChild(title);
const author = document.createElement('p');
author.innerText = book.author;
cards.appendChild(author);
const pages = document.createElement('p');
pages.innerText = `${book.pages} pages`;
cards.appendChild(pages);
const genre = document.createElement('p');
genre.innerText = book.genre;
cards.appendChild(genre);
const statusContainer = document.createElement('div');
statusContainer.setAttribute('class', 'read-status');
const statusLabel = document.createElement('p');
statusLabel.innerText = 'Status:';
statusContainer.appendChild(statusLabel);
const statusButton = document.createElement('button');
statusButton.setAttribute('class', 'read-unread');
if (readInput === 'read') {
statusButton.innerText = 'Read';
statusButton.classList.add('isRead');
} else {
statusButton.innerText = 'Unread';
statusButton.classList.add('notRead');
}
statusContainer.appendChild(statusButton);
cards.appendChild(statusContainer);
const removeBtn = document.createElement('button');
removeBtn.classList.add('remove');
removeBtn.innerText = 'Remove';
cards.appendChild(removeBtn);
cardContainer.appendChild(cards);
}
function publishCards() {
const cardContainer = document.querySelector('.card-cont');
const cards = document.querySelectorAll('.book-card');
cards.forEach((card) => cardContainer.removeChild(card));
for (let i = 0; i < myLibrary.length; i++) {
createNewCard(myLibrary[i]);
}
}
const bookForm = document.querySelector('.book-form');
bookForm.addEventListener('submit', (e) => {
e.preventDefault();
closeModal();
addBook();
publishCards();
bookForm.reset();
});
function changeReadStatus() {
if (statusButton.classList.contains('isRead')) {
statusButton.classList.remove('isRead');
statusButton.classList.add('notRead');
statusButton.innerText = 'Unread'
} else {
statusButton.classList.remove('notRead');
statusButton.classList.add('isRead');
statusButton.innerText = 'Read'
}
}
const statusButton = document.querySelector('.read-unread');
statusButton.addEventListener('click', () => {
changeReadStatus();
});
console.log(myLibrary);
<!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="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Open+Sans:ital,wght#0,300;0,400;0,500;0,600;0,700;0,800;1,300;1,400;1,500;1,600;1,700;1,800&family=Poppins:ital,wght#0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&family=Roboto:ital,wght#0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&display=swap"
rel="stylesheet">
<link rel="stylesheet" href="font-awesome-css/fontawesome.css">
<link rel="stylesheet" href="styles.css">
<title>Library Project</title>
</head>
<body>
<header>
<div class="logo">
<i class="fa-solid fa-book"></i>
<h1 class="title"> your libary</h1>
</div>
<button class="sign-in">sign in</button>
</header>
<div class="main">
<button class="add">+ Add Book</button>
<div class="card-cont">
<div class="book-card">
<p>The Cat in the Hat</p>
<p>Dr. Seuss</p>
<p>61 pages</p>
<p>Children's Literature</p>
<div class="read-status">
<p>Status:</p>
<button class="read-unread isRead">Read</button>
</div>
<button class="remove">Remove</button>
</div>
</div>
</div>
<div class="modal">
<form action="#" method="post" class="book-form">
<div class="close-btn-cont">
<button class="close-btn">×</button>
</div>
<h2>What Are You Reading?</h2>
<input type="text" id="title" name="title" placeholder="Title" required>
<input type="text" id="author" name="author" placeholder="Author" required>
<input type="text" id="pages" name="pages" placeholder="# of Pages" pattern="\d+" required>
<input type="text" id="genre" name="genre" placeholder="Genre" required>
<p class="read">Have you read this book?</p>
<div class="radio-cont">
<input type="radio" name="read" id="yes" value="yes" required>
<label for="yes">Yes</label>
<input type="radio" name="read" id="no" value="no" required>
<label for="no">No</label>
</div>
<input type="submit" id="submit" value="Submit">
</form>
</div>
<div class="overlay"></div>
<script src="https://kit.fontawesome.com/817495898e.js" crossorigin="anonymous"></script>
<script src="script.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 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>
My Js creates a div("log-entry") with a table(contents are input values) after each form submit.
My problem is that all the created tables have a identical ID, if I try to export these tables with SheetJs only the first created table gets exported but i want the whole "log"/all tables exported to the same sheet.
I tried to wrap the table around my log but couldn't manage to make it work that way.
HTML Site
The SheetJS snippet is all the way at the bottom
<!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" />
<base target="_top" />
<title>-</title>
<link rel="stylesheet" href="https://static.staticsave.com/lottie/stylesheet.css">
<!-- jQuery & Decimal Input Plugin -->
<script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.16/jquery.mask.min.js" integrity="sha512-pHVGpX7F/27yZ0ISY+VVjyULApbDlD0/X0rgGbTqCE7WFW5MezNTWG/dnhtbBuICzsd0WQPgpE4REBLv+UqChw==" crossorigin="anonymous"></script>
<!-- SheetJS Library -->
<script type="text/javascript" src="https://unpkg.com/xlsx#0.15.1/dist/xlsx.full.min.js"></script>
</head>
<body>
<div class="logo-text-wrapper">
<p>
<img
src="https://scontent-muc2-1.xx.fbcdn.net/v/t39.30808-1/277464704_400510965219536_7135106775534792654_n.jpg?stp=dst-jpg_p148x148&_nc_cat=101&ccb=1-7&_nc_sid=1eb0c7&_nc_ohc=ACTsME9JaDsAX-R7bsd&_nc_ht=scontent-muc2-1.xx&oh=00_AT-Rz2SmBYtbhy06EjZdzLe7w9duM8mIp8W0mRYX7fvwzQ&oe=6344B0CB"
alt="logo"
width="40px"
height="auto"
/>
<span id="title">PCR-Rechner</span>
</p>
<div class="actionBtns">
<button class="actionBtn calcBtn">PCR-Rechner</button>
<button class="actionBtn egensBtn">EGENS-Tool</button>
<button class="moveBtn">PCR-Rechner</button>
</div>
</div>
<main>
<form class="calc-form-wrapper" id="calc-form">
<div class="inputblock-wrapper-ID">
<label class="inputlabel" for="ID">Probenummer</label>
<input
type="number"
name="ID"
id="ID"
class="inputfield"
step="0.01"
maxlength="8"
oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);"
placeholder="Probenummer eingeben..."
onkeydown="return event.keyCode !== 69"
disabled
required
/>
<div class="inputcheckboxwrapper">
<label class="toggler-wrapper formstyle" id="toggler-wrapper">
<input type="checkbox" id="checkbox" />
<div class="toggler-slider">
<div class="toggler-knob"></div>
</div>
</label>
<label class="inputcheckboxlabel" for="checkbox"
>Mit Probennummer verwenden.</label
>
</div>
</div>
<div class="calculator">
<div class="inputblock-wrapper">
<label class="inputlabel" for="ct1"
><span id="FAM-label">FAM</span> Wert</label
>
<input
type="number"
name="ct1"
id="ct1"
class="inputfield"
step="0.01"
maxlength="5"
oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);"
onkeydown="return event.keyCode !== 69"
required
/>
</div>
<div class="inputblock-wrapper">
<label class="inputlabel" for="ct2"
><span id="CY5-label">CY5</span> Wert</label
>
<input
type="number"
name="ct2"
id="ct2"
class="inputfield"
step="0.01"
maxlength="5"
oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);"
onkeydown="return event.keyCode !== 69"
required
/>
</div>
</div>
<div class="result-wrapper">
<label class="result-label">CT <span>=</span></label>
<div class="result-wrapper inner">
<input class="inputfield result" id="result" name="result" tabindex="-1" />
<div class="copy-button tooltip" id="copy-button">
<svg
version="1.1"
width="18"
height="18"
viewBox="0 0 64 64"
xml:space="preserve"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="m53.979 9.1429h-3.9683c-0.082699 0-0.1562 0.0284-0.2331 0.047v-4.1671c0-2.7698-2.3046-5.0228-5.1379-5.0228h-34.423c-2.8333 0-5.1379 2.253-5.1379 5.0228v46.843c0 2.7698 2.3046 5.0228 5.1379 5.0228h6.0367v2.2679c0 2.6706 2.2163 4.8432 4.9415 4.8432h32.784c2.7252 0 4.9415-2.1726 4.9415-4.8432v-45.171c-1.8e-6 -2.6706-2.2163-4.8432-4.9415-4.8432zm-46.868 42.723v-46.843c0-1.6488 1.3939-2.991 3.1062-2.991h34.423c1.7123 0 3.1062 1.3422 3.1062 2.991v46.843c0 1.6488-1.3939 2.9911-3.1062 2.9911h-34.423c-1.7123 4e-7 -3.1062-1.3423-3.1062-2.9911zm49.778 7.2907c0 1.5506-1.3055 2.8115-2.9097 2.8115h-32.784c-1.6042 0-2.9098-1.2609-2.9098-2.8115v-2.2679h26.354c2.8333 0 5.1379-2.253 5.1379-5.0228v-40.739c0.0769 0.0186 0.1504 0.047 0.2331 0.047h3.9683c1.6042 0 2.9097 1.2609 2.9097 2.8115v45.171z"
/>
<path
d="m38.603 13.206h-22.349c-0.5615 0-1.0159 0.4543-1.0159 1.0158 0 0.5616 0.4544 1.0159 1.0159 1.0159h22.349c0.5615 0 1.0159-0.4543 1.0159-1.0159 0-0.5615-0.4544-1.0158-1.0159-1.0158z"
/>
<path
d="m38.603 21.333h-22.349c-0.5615 0-1.0159 0.4543-1.0159 1.0158 0 0.5615 0.4544 1.0159 1.0159 1.0159h22.349c0.5615 0 1.0159-0.4544 1.0159-1.0159 0-0.5615-0.4544-1.0158-1.0159-1.0158z"
/>
<path
d="m38.603 29.46h-22.349c-0.5615 0-1.0159 0.4544-1.0159 1.0159s0.4544 1.0159 1.0159 1.0159h22.349c0.5615 0 1.0159-0.4544 1.0159-1.0159s-0.4544-1.0159-1.0159-1.0159z"
/>
<path
d="m28.444 37.587h-12.19c-0.5615 0-1.0159 0.4544-1.0159 1.0159s0.4544 1.0159 1.0159 1.0159h12.19c0.5615 0 1.0158-0.4544 1.0158-1.0159s-0.4543-1.0159-1.0158-1.0159z"
/>
</svg>
<div class="top">
<p id="tooltip-content">Ergebniss kopieren.</p>
<i></i>
</div>
</div>
</div>
</div>
<button
type="submit"
class="submit-button"
id="calcbutton"
onclick="this.blur();"
>
CT Berechnen
</button>
<button onclick="ExportToExcel()">Test export</button>
</form>
<div class="log-scroll-wrapper">
<div class="log-wrapper" id="log-wrapper">
<!-- Log entries are displayed here -->
<!-- <div class="log-entry">
<table class="log-entry-table">
<thead>
<tr class="log-entry-table-tr">
<td><span>99</span>.</td>
<td>ID<span>:</span> <span>30715407</span></td>
<td>CT<span>:</span> <span>34.3444</span></td>
<td>Zeit<span>:</span> <span>20:20:20</span></td>
</tr>
</thead>
</table>
</div> -->
</div>
</div>
</main>
<script>
const ct1 = document.getElementById("ct1");
const ct2 = document.getElementById("ct2");
const calcBtn = document.querySelector(".calcBtn");
const egensBtn = document.querySelector(".egensBtn");
const moveBtn = document.querySelector(".moveBtn");
const copyBtn = document.querySelector("#copy-button");
const result = document.querySelector("#result");
const calcForm = document.querySelector("#calc-form");
const idinput = document.getElementById("ID");
const logWrapper = document.getElementById("log-wrapper");
const title = document.getElementById("title");
const uploadForm = document.getElementById("upload-form");
let logcounter = 0;
setListeners();
function handleCalcForm(event) {
event.preventDefault();
const h =
(new Date().getHours() < 10 ? "0" : "") + new Date().getHours();
const m =
(new Date().getMinutes() < 10 ? "0" : "") + new Date().getMinutes();
const s =
(new Date().getSeconds() < 10 ? "0" : "") + new Date().getSeconds();
const timestamp = h + ":" + m + ":" + s;
const ct1val = ct1.value;
const ct2val = ct2.value;
const addition = +ct1val + +ct2val;
const division = addition / 2;
const idval = idinput.value;
logcounter += 1;
result.value = division;
ct1.value = ""
ct2.value = ""
const logEntry = document.createElement("div");
logEntry.classList.add("log-entry");
logEntry.innerHTML = `
<table class="log-entry-table" id="log-entry-table">
<thead>
<tr class="log-entry-table-tr">
<td><span>${logcounter}</span>.</td>
<td>ID<span>:</span> <span>${idval ? idval : "-"}</span></td>
<td>CT<span>:</span> <span>${division}</span></td>
<td>Zeit<span>:</span> <span>${timestamp}</span></td>
</tr>
</thead>
</table>
`;
logWrapper.appendChild(logEntry);
}
function setListeners() {
$("#upload-button").on("click", function ( ){
alert("Entschuldige, dieses Tool befindet sich noch in der Entwicklung :/")
});
$(document).ready(function () {
$(ct1).mask('00.00', { reverse: true });
$(ct2).mask('00.00', { reverse: true });
});
$(function () {
$("#checkbox").on("click", function () {
$("#ID").attr("disabled", !$(this).is(":checked"));
$("#ID").val([], !$(this).is(":checked"));
});
});
calcForm.addEventListener("submit", (event) => {
handleCalcForm(event);
});
copyBtn.addEventListener("click", (event) => {
event.preventDefault();
result.select();
result.setSelectionRange(0, 99999);
navigator.clipboard.writeText(result.value);
document.getElementById("tooltip-content").innerText = "Kopiert!";
});
result.addEventListener("focusout", (event) => {
document.getElementById("tooltip-content").innerText =
"Ergebniss kopieren.";
});
egensBtn.addEventListener("click", () => {
moveBtn.classList.add("rightBtn");
title.innerText = "EGENS-Tool";
calcForm.style.display = "none";
logWrapper.style.display = "none";
uploadForm.style.display = "flex";
moveBtn.innerText = "EGENS-Tool";
});
calcBtn.addEventListener("click", () => {
moveBtn.classList.remove("rightBtn");
title.innerText = "PCR-Rechner";
calcForm.style.display = "flex";
logWrapper.style.display = "flex";
uploadForm.style.display = "none";
moveBtn.innerText = "PCR-Rechner";
});
}
//File input
var inputs = document.querySelectorAll('.file-input')
for (var i = 0, len = inputs.length; i < len; i++) {
customInput(inputs[i])
}
function customInput (el) {
const fileInput = el.querySelector('[type="file"]')
const label = el.querySelector('[data-js-label]')
fileInput.onchange =
fileInput.onmouseout = function () {
if (!fileInput.value) return
var value = fileInput.value.replace(/^.*[\\\/]/, '')
el.className += ' -chosen'
label.innerText = value
}
}
//Start Dropdown
// function getSelectedValue(id) {
// return $("#" + id).find("dt a span.value").html();
// }
// $("button").click(function(e){
// var val = getSelectedValue('locations');
// alert(val);
// });
$(".dropdown dt a").click(function(e) {
$(".dropdown dd ul").toggle();
e.preventDefault();
});
$(".dropdown dd ul li a").click(function() {
var text = $(this).html();
$(".dropdown dt a span").html(text);
$(".dropdown dd ul").hide();
});
$(document).bind('click', function(e) {
var $clicked = $(e.target);
if (! $clicked.parents().hasClass("dropdown"))
$(".dropdown dd ul").hide();
});
//End Dropdown
// $(function() {
// tmpval = $('#result').val();
// if(tmpval == '') {
// $('#copy-button').addClass('button-disabled');
// } else if(tmpval != "") {
// $('#copy-button').removeClass('button-disabled');
// }
// });
///SheetJS export
function ExportToExcel(type, fn, dl) {
var elt = document.getElementById('log-entry-table');
var wb = XLSX.utils.table_to_book(elt, { sheet: "Logs" });
return dl ?
XLSX.write(wb, { bookType: type, bookSST: true, type: 'base64' }):
XLSX.writeFile(wb, fn || ('Log Test.' + (type || 'xlsx')));
}
</script>
</body>
</html>
I have a field "total" which calculates the product of 'price per kWH, 'KwH', and 'Hours used'. I would like to dynamically change the output of all 'total' fields if the user retrospectively changes the value of 'price per KwH'. Currently, only the latest added total field recalculates the product when changing the price value.
var idNumber= 1;
var deviceID = "device_"+idNumber;
var kWattID = "kW_"+idNumber;
var hoursID = "hours_"+idNumber;
var totalID = "total_"+idNumber;
function createNewInputFields() {
// console.log("In createNewInputFields - Given number:"+idNumber);
idNumber = idNumber+1;
// console.log("In createNewInputFields - after increase:"+idNumber);
deviceID = "device_"+idNumber;
kWattID = "kW_"+idNumber;
hoursID = "hours_"+idNumber;
totalID = "total_"+idNumber;
// console.log("In createNewInputFields() - "+deviceID);
// console.log("In createNewInputFields() - "+kWattID);
// console.log("In createNewInputFields() - "+hoursID);
// console.log("In createNewInputFields() - "+totalID);
const containerDevice = document.getElementById('deviceCol');
const containerkWatt = document.getElementById('kWattsCol');
const containerHours = document.getElementById('hoursCol');
const containerTotal = document.getElementById('totalCol');
const inputHtmlDevice = "<input type='text' id="+deviceID+" required>";
const inputHtmlkWatt = "<br> <input type='text' oninput='calculate()' id="+kWattID+" required>";
const inputHtmlHours = "<input type='text' oninput='calculate()' id="+hoursID+" required>";
const inputHtmlTotal = "<input type='text' id="+totalID+" required readonly>";
containerDevice.insertAdjacentHTML('beforeend', inputHtmlDevice);
containerkWatt.insertAdjacentHTML('beforeend', inputHtmlkWatt);
containerHours.insertAdjacentHTML('beforeend', inputHtmlHours);
containerTotal.insertAdjacentHTML('beforeend', inputHtmlTotal);
return idNumber;
}
// function to correctly round up to the third decimal
function precisionRound(number) {
var factor = Math.pow(10, 4);
return Math.round(number * factor) / factor;
}
function calculate(){
// console.log("In calculate() - idNumber: "+idNumber);
deviceID = "device_"+idNumber;
kWattID = "kW_"+idNumber;
hoursID = "hours_"+idNumber;
totalID = "total_"+idNumber;
// console.log("In calculate() - : "+deviceID);
// console.log("In calculate() - : "+kWattID);
// console.log("In calculate() - : "+hoursID);
// console.log("In calculate() - : "+totalID);
var kW = document.getElementById(kWattID).value;
var kW = parseFloat(kW).toFixed(3);
var hours = document.getElementById(hoursID).value;
var hours = parseFloat(hours).toFixed(3);
var kwH_rate = document.getElementById("energyrate").value
var total = kwH_rate * (kW * hours);
var total = precisionRound(total)
document.getElementById(totalID).value = total;
}
body {
background: transparent;
color: #fcbe24;
padding: 0 24px;
margin: 0;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="src/style.css">
</head>
<body>
<div class="intro">
<p> Enter your energy company's electricity rate per kWh: <input type="text" class="energyrate" oninput="calculate()" id="energyrate" required></p>
</div>
<div class="row">
<div class="deviceCol" id="deviceCol">
<p><b>Device</b></p>
<input type="text" id="device_1" required>
<!-- device name watts hours in use total -->
</div>
<div class="kWattsCol" id="kWattsCol">
<p><b>kWh</b></p>
<input type="text" oninput="calculate()" id="kW_1" required>
<!-- <input type="text" id="kW_1" required> -->
</div>
<div class="hoursCol" id="hoursCol">
<p><b>Hours used</b></p>
<input type="text" oninput="calculate()" id="hours_1" required>
<!-- <input type="text" onkeypress="calculate(idNumber)" id="hours_1"required> -->
</div>
<div class="totalCol" id="totalCol">
<p><b>Total</b></p>
<input type="text" id="total_1" readonly>
</div>
<button class="btn" onclick="createNewInputFields(idNumber)">Add another item</button>
</div>
<h1 id="header"></h1>
<script src="src/script.js"></script>
</body>
</html>
[I'm simply trying to make a form that allows you to select which box the user's name and password will display in. The code I have works fine but I'm curious to see how it could be refactored to be less repetitive. I thought of using a JS object but I'm not sure how to go about that in this instance. Any help would be appreciated! Here is a link to the CodePen: (https://codepen.io/TOOTCODER/pen/yLeagRq)
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Which Box?</title>
<style>
.square{
border: 1px solid black;
width: 15rem;
height: 15rem;
float: left;
}
#formContainer {
position: relative;
top: 16rem;
left: -45.5rem;
}
.boxTitle {
text-align: center;
margin-top: 1em;
}
.boxOutputContainer {
text-align: center;
}
</style>
</head>
<body>
<div class="square">
<h1 class="boxTitle">BOX1</h1>
<div class="boxOutputContainer">
<div id="b1NameOutput"></div>
<div id="b1PasswordOutput"></div>
</div>
</div>
<div class="square">
<h1 class="boxTitle">BOX2</h1>
<div class="boxOutputContainer">
<div id="b2NameOutput"></div>
<div id="b2PasswordOutput"></div>
</div>
</div>
<div class="square">
<h1 class="boxTitle">BOX3</h1>
<div class="boxOutputContainer">
<div id="b3NameOutput"></div>
<div id="b3PasswordOutput"></div>
</div>
</div>
<div id="formContainer">
<form>
<label for="name">Name:</label>
<input required type="text" id="name">
<label for="name">Password:</label>
<input required type="text" id="password">
<label for="boxSelect">Which box?</label>
<select id="boxSelect">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<input type="submit" id="submitBtn">
</form>
</div>
<script>
var submitBtn = document.querySelector("#submitBtn");
var resetBtn = document.querySelector("#resetBtn");
submitBtn.addEventListener("click", function(){
event.preventDefault();
var name = document.querySelector("#name");
var password = document.querySelector("#password");
var boxSelect = document.querySelector("#boxSelect");
var b1NameOutput = document.querySelector("#b1NameOutput");
var b1PasswordOutput = document.querySelector("#b1PasswordOutput");
var b2NameOutput = document.querySelector("#b2NameOutput");
var b2PasswordOutput = document.querySelector("#b2PasswordOutput");
var b3NameOutput = document.querySelector("#b3NameOutput");
var b3PasswordOutput = document.querySelector("#b3PasswordOutput");
if(boxSelect.value == 1){
b1NameOutput.innerHTML = "<p>"+name.value+"</p>";
b1PasswordOutput.innerHTML = "<p>"+password.value+"</p>";
}else if(boxSelect.value == 2){
b2NameOutput.innerHTML = "<p>"+name.value+"</p>";
b2PasswordOutput.innerHTML = "<p>"+password.value+"</p>";
}else if(boxSelect.value == 3){
b3NameOutput.innerHTML = "<p>"+name.value+"</p>";
b3PasswordOutput.innerHTML = "<p>"+password.value+"</p>";
}});
</script>
</body>
</html>
I see someone beat me to the answer but here is another option that is easy to refactor.
var submitBtn = document.querySelector("#submitBtn");
var resetBtn = document.querySelector("#resetBtn");
submitBtn.addEventListener("click", function(){
event.preventDefault();
var name = document.querySelector("#name");
var password = document.querySelector("#password");
var boxSelect = document.querySelector("#boxSelect");
var nameId = `#b${boxSelect.value}NameOutput`;
var passwordId = `#b${boxSelect.value}PasswordOutput`;
var nameOutput = document.querySelector(nameId);
nameOutput.innerHTML = "<p>"+name.value+"</p>";
var passwordOutput = document.querySelector(passwordId);
passwordOutput.innerHTML = "<p>"+password.value+"</p>";
});