How to calculate and distribute the result on html? - javascript

I have two values on my html: "Money" and "Time", and those values come from Session Storage, depending on what the person filled previously on another html page.
So lets say the person filled that they need to pay $100 in 2 days.
What i'm trying to do, is to create a list, showing the number of payments, with the amount to be paid in each payment. Like the example below
MONEY: $100 /
TIME: 2 Days
RESULT:
$50
$50
So if the person has 5 days, instead of 2, it would appear as:
$20
$20
$20
$20
$20
What i have so far is:
HTML
<p id="money-value"></p>
<p id="time-value"></p>
<div id="payments"></div>
<script>
const displayMoney = document.getElementById("money-value");
const storedMoney = sessionStorage.getItem("Money");
window.addEventListener("load", () => {
displayMoney.innerHTML = "Money: " + storedMoney
});
const displayTime = document.getElementById("time-value");
const storedTime = sessionStorage.getItem("Time");
window.addEventListener("load", () => {
displayTime.innerHTML = "Time: " + storedTime
});
</script>
What i'm trying to do here, is to use Javascript to create a list element, inside the <div id="payments> that would not only calculate the amount to be paid in each payment, but also that the number of "topics" (payments) would increase, according to the number of "time" the person has (Just like the example i gave).

This might be the result you wanted. But I'm pretty sure that there are better ways to program this.
const displayMoney = document.getElementById("money-value");
const storedMoney = 100; //example
window.addEventListener("load", () => {
displayMoney.innerHTML = "Money: " + storedMoney
});
const displayTime = document.getElementById("time-value");
const storedTime = 5;//example
window.addEventListener("load", () => {
displayTime.innerHTML = "Time: " + storedTime
});
var calc = storedMoney / storedTime;
for (let i = 0; i < storedTime; i++) {
var list = document.createElement("li");
list.innerText = `${calc}`;
document.body.appendChild(list);
}
<p id="money-value"></p>
<p id="time-value"></p>
<div id="payments"></div>

Related

How to save budget list in local storage?

I know local storage is not a secure solution for this, but for now, I am doing it this way for practice.
I think I am on the right track here, I want my created list for the budget app to store, this method seems to store the first created list.
/*----Store Stored budget list----*/
function storedEntry(){
const saveData = makeNewBudget();
const myJSON = JSON.stringify(saveData);
window.localStorage.setItem(STORAGE_KEY, myJSON);
}
I think what needs to happen is get that same method to work for the array.
let budgetArray = [];
I tried this method, but gives a JSON error, sop for some reason it's not converted to JSON
let budgetArray = JSON.parse(window.localStorage.getItem(STORAGE_KEY) ?? "[]");
End result should be set local storage for array in its own function and get the stored information when checking the array.
I put the entire JS code so you can see what is going on
/*----Generate ID----*/
const createId = () =>`${Math.floor(Math.random() * 10000)}$(new Date().getTime())}`;
/*----Get current Date----*/
function createdDate() {
let currentDate = new Date();
let day = String(currentDate.getDate()).padStart(2, '0');
let month = String(currentDate.getMonth() + 1).padStart(2, '0');
let year = currentDate.getFullYear();
currentDate = month + '/' + day + '/' + year;
console.log(currentDate)
return currentDate;
}
/*----Variable Objects----*/
const el = {
list: document.querySelector(".list"),
cashflow: document.querySelector("#cashflow"),
catagory: document.querySelector(".catagory"),
label: document.querySelector(".label"),
number: document.querySelector(".number"),
};
/*----Array with local Storage----*/
let budgetArray = [];
/*----Budget list Object----*/
function makeNewBudget(){
const data = {
id: createId(),
cashflowNew: el.cashflow.value,
catagoryNew: el.catagory.value,
labelNew: el.label.value,
dateNew: createdDate(),
numberNew: el.number.value,
};
return data;
}
/*----Render Budget List----*/
function renderList(){
el.list.innerHTML = budgetArray.map(function (data,i) {
return `<div class="entry">
<div class="list">
<button onclick="deleteItem(event, ${i})" class="Archive" data-id="${data.id}">
<img src="../resources/Images/archive.png" alt="Archive">
</button>
<button onclick="editItem(event, ${i})" class = "edit" data-id="${data.id}" class = "edit" data-id="${data.id}">
<img src="../resources/Images/edit.png" alt="Edit">
</button>
<div class="input" data-id="${data.id}"></div>
<label class="dateNew">${data.dateNew}</label>
<label class="cashflowNew">${data.cashflowNew}</label>
<label class="catagoryNew">${data.catagoryNew}</label>
<label class="labelNew">${data.labelNew}</label>
<label class="numberNew">${data.numberNew}</label>
</div>
</div>
<label class="total"></label>`;
});
}
/*----form validation----*/
let budgetButton = document.querySelector(".budget-button");
let label = document.querySelector(".label");
let num = document.querySelector(".number");
let entry = document.querySelector(".entry")
budgetButton.addEventListener("click", () => {
if (!label.value || !num.value) {
alert("please make sure all inputs are filled");
}
budgetArray.push(makeNewBudget())
renderList();
storedEntry();
});
/*----Archive list----*/
function deleteItem(event, i){
}
/*----Store Stored budget list----*/
function storedEntry(){
const saveData = makeNewBudget();
const myJSON = JSON.stringify(saveData);
window.localStorage.setItem(STORAGE_KEY, myJSON);
}

Dynamically display sales tax when I select a state?

I am a student working on an assignment. The assignment is to
create an array that lists states
create a parallel array that lists state taxes
use JS to dynamically load the lists of states into the drop down menu
create a function that will display the tax rate using parallel state array...they want us to use a loop
I am stuck on the final part where I create a function using loops that will display the sales tax. My code is below.
let states = ["state1", "state2", "state3", "state4"];
let salesTax = ["6%", "11%", "7%", "8%"];
function displayTax(){
for(x=0; x < states.length; x++){
document.getElementById("displayTaxPercent").innerHTML = salesTax[x];
}
}
When I do this I just get 8% over and over again.
The reason you are getting value as 8% is because you are not giving the selected value and code is simply iterating through all values and hence it will always show last value.
Here is simple example
let states = ["state1", "state2", "state3", "state4"];
let salesTax = ["6%", "11%", "7%", "8%"];
function displayTax(state){
console.log(state + " : " + salesTax[states.indexOf(state)])
//document.getElementById("displayTaxPercent").innerHTML = salesTax[states.indexOf(state)];
}
displayTax("state1");
displayTax("state3");
const stateSelect = document.querySelector("#stateSelect");
let states = ["state1", "state2", "state3", "state4"];
let salesTax = ["6%", "11%", "7%", "8%"];
stateSelect.append(
...states.map((state, stateI) => {
const optionEl = document.createElement("option");
optionEl.value = stateI;
optionEl.innerText = state;
return optionEl;
})
);
const display = () => {
document.querySelector("#results").innerText =
"Sales tax in " +
states[stateSelect.value] +
" is " +
salesTax[stateSelect.value];
};
stateSelect.addEventListener("change", display);
display();
<select id="stateSelect">
</select>
<p id="results"></p>

adding event listeners in Javascript is doubling my (simple) maths

I will attempt to be as concise as possible, but am out of my depth (i should be in the baby pool :)
I'm trying to make a simple website for my son that presents a random sentence with a blank where an adverb should be. The user then has to guess which of the three randomised words presented below is an adverb. I have then tried to implement a scoring system which is where my problem lies.
I had it working OK, when the buttons were static, but since randomising and adding event listeners to the answer buttons it is adding two to the score instead of one. The problem code is towards the bottom (//add event listeners to buttons)
One further problem is that when someone answers the first question incorrectly my code says they have 'undefined correct answers'. I can't get that to say '0 correct answers'
<head>
<title>Adverb Kings</title>
</head>
<body>
<h1>Adverb Kings</h1>
<div id="sentence"></div>
<div>
<button type="button" onclick="right()"></button>
<button type="button" onclick="wrong()"></button>
<button type="button" onclick="wrong()"></button>
<div id="result"></div>
<div id="correct"></div>
<div id="attempted"></div>
</div>
<script>
//define right functions
function right() {
correctAlert();
correctAnswer();
answersAttempted();
}
//define wrong functions
function wrong() {
incorrectAlert();
answersAttempted();
}
//alert correct
function correctAlert() {
var element = document.getElementById("result");
element.classList.add("correct");
element.innerHTML = "Correct";
}
//alert incorrect
function incorrectAlert() {
var element = document.getElementById("result");
element.classList.add("incorrect");
element.innerHTML = "Incorrect, try again.";
}
//tracking correct answers
function correctAnswer() {
if (sessionStorage.correct) {sessionStorage.correct = Number(sessionStorage.correct)+1;
} else {
sessionStorage.correct = 1;
}
}
//tracking attempted questions count
function answersAttempted() {
if (typeof(Storage) !== "undefined") {
if (sessionStorage.attempts) {
sessionStorage.attempts = Number(sessionStorage.attempts)+1;
} else {
sessionStorage.attempts = 1;
}
document.getElementById("attempted").innerHTML = "You have attempted " + sessionStorage.attempts + " question(s) in this session and got " + sessionStorage.correct + " correct" ;
} else {
document.getElementById("attempted").innerHTML = "Sorry, your browser does not support web storage...";
}
}
//create sentence array
var sentence;
sentence = ['The people _______ went crazy about the new game options', 'The man _______ slipped his hands around his desk handle', 'He _______ typed a new password for his school account'];
//randomise sentence array
var el = document.getElementById('sentence');
el.textContent = sentence[Math.floor(Math.random() * sentence.length)];
//set order of words in order to randomise
var orders = [0, 1, 2];
shuffle(orders);
//add event listeners to buttons
var buttons = document.getElementsByTagName("button");
buttons[orders[0]].addEventListener('click', right);
buttons[orders[1]].addEventListener('click', wrong);
buttons[orders[2]].addEventListener('click', wrong);
//create and randomise adverb array
var adverbs = ['slowly', 'quickly', 'insanely'];
buttons[orders[0]].textContent = adverbs[Math.floor(Math.random() * adverbs.length)];
//create and randomise other words
var other1 = ['burger', 'insane', 'ugly'];
buttons[orders[1]].textContent = other1[Math.floor(Math.random() * other1.length)];
var other2 = ['sausage', 'fist', 'gun'];
buttons[orders[2]].textContent = other2[Math.floor(Math.random() * other2.length)];
//shuffle position of adverb
function shuffle(array) {
array.sort(() => Math.random() - 0.5);
}
</script>
</body>
</html>```
You are adding the event listeners both in the HTML and JS.
Remove the onclick="..." part of the buttons in the HTML and all should be good.
To stop the number being undefined, set sessionStorage.correct to 0 before you call any functions:
<script>
sessionStorage.correct = 0;
...
You have added event listener twice on in HTML and one in js code due to which it is hitting twice.
regarding the undefined value, when hitting incorrect first-time session storage is not initialized due to which it is showing undefined. please check below js code where I have commented the js event listener and initialize the sessionstorage.correct and now it is working fine.
code
//define right functions
function right() {
correctAlert();
correctAnswer();
answersAttempted();
}
//define wrong functions
function wrong() {
incorrectAlert();
answersAttempted();
}
//alert correct
function correctAlert() {
var element = document.getElementById("result");
element.classList.add("correct");
element.innerHTML = "Correct";
}
//alert incorrect
function incorrectAlert() {
var element = document.getElementById("result");
element.classList.add("incorrect");
element.innerHTML = "Incorrect, try again.";
}
//tracking correct answers
function correctAnswer() {
if (sessionStorage.correct) {sessionStorage.correct = Number(sessionStorage.correct)+1;
} else {
sessionStorage.correct = 1;
}
}
//tracking attempted questions count
function answersAttempted() {
if (typeof(Storage) !== "undefined") {
if (sessionStorage.attempts) {
sessionStorage.attempts = Number(sessionStorage.attempts)+1;
} else {
sessionStorage.attempts = 1;
}
// initializing sessionStorage.correct
if(!sessionStorage.correct) {
sessionStorage.correct=0;
}
document.getElementById("attempted").innerHTML = "You have attempted " + sessionStorage.attempts + " question(s) in this session and got " + sessionStorage.correct + " correct" ;
} else {
document.getElementById("attempted").innerHTML = "Sorry, your browser does not support web storage...";
}
}
//create sentence array
var sentence;
sentence = ['The people _______ went crazy about the new game options', 'The man _______ slipped his hands around his desk handle', 'He _______ typed a new password for his school account'];
//randomise sentence array
var el = document.getElementById('sentence');
el.textContent = sentence[Math.floor(Math.random() * sentence.length)];
//set order of words in order to randomise
var orders = [0, 1, 2];
shuffle(orders);
//add event listeners to buttons
var buttons = document.getElementsByTagName("button");
// buttons[orders[0]].addEventListener('click', right);
// buttons[orders[1]].addEventListener('click', wrong);
// buttons[orders[2]].addEventListener('click', wrong);
//create and randomise adverb array
var adverbs = ['slowly', 'quickly', 'insanely'];
buttons[orders[0]].textContent = adverbs[Math.floor(Math.random() * adverbs.length)];
//create and randomise other words
var other1 = ['burger', 'insane', 'ugly'];
buttons[orders[1]].textContent = other1[Math.floor(Math.random() * other1.length)];
var other2 = ['sausage', 'fist', 'gun'];
buttons[orders[2]].textContent = other2[Math.floor(Math.random() * other2.length)];
//shuffle position of adverb
function shuffle(array) {
array.sort(() => Math.random() - 0.5);
}

How to create multiple variables dynamically that can be summed up

I have a variable that gets its value once an ID is clicked, via .innerText
var currentID = e.target.id;
I need the value of this variable, currentID, to be stored in a new variable which is named just like the ID of which it got its value.
So, if a user clicks an element with the ID price1, and the price is 200.
A new variable with the name price1 with value 200 should be created.
Then, I want to sum up the new variables: price1+price2+price3 etc = totalprice.
This is what I'm doing right now:
$('div.unselected-option').click(function(e) {
$(this).toggleClass("selected-option unselected-option")
if ($(this).hasClass("selected-option")) {
var currentID = e.target.id;
console.log(currentID);
var price1 = document.getElementById(currentID).innerText
var finalprice
finalprice = +price1;
document.getElementById("showprice2").innerHTML = finalprice
Here's an image of the design:
I can't seem to figure this out... What I'm doing right now just results in having 1 variable which means I cannot sum anything up... I would love your view on this issue!
Your use case is pretty strange I hope your backend is secured and well made.
Here is a potential solution:
<div id="a1" onclick="handleProductClick">20</div>
<div id="a2" onclick="handleProductClick">40</div>
<div id="b1" onclick="handleProductClick">20</div>
<div id="b2" onclick="handleProductClick">60</div>
...
<div id="total-price">0</div>
...
const basket = {}
function addToBasket(event) {
const { id, innerText } = event.target
const price = parseInt(innertText, 10)
const product = basket[id]
const count = product.count || 1
basket[id] = {
price,
count
}
}
function getBasketTotalPrice = () => {
return Object.keys(basket)
.reduce((total, product) => total + product.count * product.price, 0)
}
function handleProductClick = (event) => {
addToBasket(event)
const totalPrice = getBasketTotalPrice()
document.querySelector('#total-price').innerHTML = totalPrice
}

Whether I have implemented modular javaScript with mixins the right way?

I am learning to write modular based javaScript coding.
I came across mixins while reading javascript patterns.
Hence I am trying to understand modular style javascript and mixins by
implementing in a few examples.
My example has Employee where an employee can be a contractual employee or a
full time employee.
Contractual employee get paid on hourly basis, whereas an full time get monthly salary with benefits.
the code for the above scenario is as follows,
// and employee module which is common
var employeeModule = (function(){
// private variables
var name = "",
address = "",
salary = 0,
module = {};
// publicly available methods
module.calculateSalary = function(unitOfWork,employeeType){
var totalPay = 0, perDayWage = 0;
if(employeeType === "CONTRACTUAL"){
totalPay = unitOfWork * salary;
}
if(employeeType === "FULLTIME"){ // full time employee also get benifits
perDayWage = salary/30;
totalPay = (perDayWage * unitOfWork) + (perDayWage * 8); // 8 days of leaves per month
totalPay += 2300; // monthly allowance for a fulltime employee
}
return totalPay;
}
module.setSalary = function(_salary){
salary = _salary;
}
module.getName = function(){
return name;
}
module.setName = function(_name){
name = _name;
}
module.getAddress = function(){
return address;
}
module.setAddress = function(addr){
address = addr;
}
module.init = init;
return module;
function init(){
name = "Rahul";
salary = 2500;
address = "India";
}
})();
// a contractual employee module
var contractualEmployeeModule = (function(emp){
var noOfHr = 0, // total number of hours worked
payableSalary = 0; // total hourly pay
var module = {};
// number of hours an contractual employee worked
module.setNoOfHrWorked = function(_noOfHr){
noOfHr = _noOfHr;
}
module.getTotalSalary = function(){
payableSalary = emp.calculateSalary(noOfHr,"CONTRACTUAL");
return payableSalary;
}
// salary rate for per hour work
module.setHourlyRate = function(rate){
emp.setSalary(rate);
}
module.setAddress = function(_address){
emp.setAddress(_address);
}
module.setName = function(_name){
emp.setName(_name);
}
module.init = function(){
emp.init();
}
module.getTotalInfo = function(){
var str = "";
str += "Name \""+emp.getName() + "\" " +
"living in \""+ emp.getAddress() +"\""+
" is contractual employee has earned "+this.getTotalSalary();
return str;
}
return module;
})(employeeModule);
// a fulltime employee module
var fulltimeEmployeeModule = (function(emp){
var noOfDays = 0, // number of days employee attended for work
payableSalary = 0; // total monthly salary an employee is eligible to earn
var module = {};
// number of hours an employee worked in a month
module.setNoOfDaysWorked = function(_noOfDays){
noOfDays = _noOfDays;
}
// calculating total monthly salary
// a fulltime employee gets
module.getTotalSalary = function(){
payableSalary = emp.calculateSalary(noOfDays,"FULLTIME");
return payableSalary;
}
// total monthly salary an fulltime employee
// should earn
module.setMonthlySalary = function(salary){
emp.setSalary(salary);
}
module.setAddress = function(_address){
emp.setAddress(_address);
}
module.setName = function(_name){
emp.setName(_name);
}
module.init = function(){
emp.init();
}
module.getTotalInfo = function(){
var str = "";
str += "Name \""+emp.getName() + "\" " +
"living in \""+ emp.getAddress() +"\""+
" is a fulltime employee has earned "+this.getTotalSalary();
return str;
}
return module;
})(employeeModule);
contractualEmployeeModule.setName("John William");
contractualEmployeeModule.setAddress("New York");
contractualEmployeeModule.setHourlyRate(12);
contractualEmployeeModule.setNoOfHrWorked(123);
console.log(contractualEmployeeModule.getTotalInfo());
fulltimeEmployeeModule.setName("Jack Harrison");
fulltimeEmployeeModule.setAddress("Sedney");
fulltimeEmployeeModule.setMonthlySalary(2300);
fulltimeEmployeeModule.setNoOfDaysWorked(25);
console.log(fulltimeEmployeeModule.getTotalInfo());
From the above code you can see that I have kept total salary calculation as part of employee, and respective to setting salary with each of the employee type.
Can you please go though the code and have a look at my approach.
Whether I am able to achieve modularity in my javaScript code.
Also the above way of coding can be done in a different way, if yes can you please give me some example.
The output of the above code is
E:\RahulShivsharan\MyPractise\DesignPatternsInJavaScript\modules>node ex03.js
Name "John William" living in "New York" is contractual employee has earned 1476
Name "Jack Harrison" living in "Sedney" is a full time employee has earned 4830

Categories

Resources