Dynamically display sales tax when I select a state? - javascript

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>

Related

How to calculate and distribute the result on html?

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>

How to output the currency type next to the converted number

I am trying to get my code to output the currency type name for example EURO, YEN AND USD next to the converted number but I seem to be having trouble, any help would be appreciated.
function tipCalculator() {
var billAmt = document.getElementById("bill").value;
var tipValue = document.getElementById("tipValue").value;
if (billAmt === "" || tipValue == 0) {
alert("Please Enter Value")
return;
}
var total = (billAmt * tipValue);
total = Math.round(total * 100) / 100;
total = total.toFixed(2);
document.getElementById("totalTip").style.display = "block";
document.getElementById("tip").innerHTML = total;
if (document.getElementById("USD")) {
document.getElementById("tip").innerHTML = total + " USD";
}
}
document.getElementById("totalTip").style.display = "none";
document.getElementById("calculate").onclick =
function() {
tipCalculator();
}
<select id="tipValue">
<option value="">--Please choose a currency--</option>
<option value ="1.30353" id="USD">USD</option>
<option value ="1.16158" id="Euro">Euro</option>
<option value ="8.75747" id="Yen">Yen</option>
<option value ="4.98785" id="Zloty">Zloty</option>
</select>
What you need to do is create an array from your currency options (USD, Euro, Yen, Zloty, etc.) and refer to that array instead of "USD" in the following if statement:
if(document.getElementById("USD")){
document.getElementById("tip").innerHTML = total + " USD";
}
Something like this:
if(document.getElementById("currency_array[]")){
document.getElementById("tip").innerHTML = total + " currency_array[]";
}
#elbrant That still has the same problem because you need to know where you are in the array. You need to pass the id to make it dynamic. So, I would make your options into click events so it can pass its id:
document.getElementById("option").onclick =
function() {
tipCalculator(this.id);
}
Don't forget to add the parameter to the function.
In the function, get rid of the if statement and do this:
document.getElementById("tip").innerHTML = total + this.id;

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

Calculate the price of the items, depending on its quantity

I'm trying to make block with the prices. The unit price varies depending on its quantity of units. For example:
Quantity — Price for each
1____________________$110
10___________________$105
20___________________$100
...
Number of items:__
Total:
Price for each:
There is a need to write a the text field into which the user enters the number of items, and everything is recalculating and summing on the fly.
Here is my realization of this task:
var price1 = 110,
price2 = 105,
price3 = 100,
qty1 = 1,
qty2 = 10,
qty3 = 20;
function conversion(val) {
var div = document.getElementById("div"),
price = document.getElementById("price");
if (isNaN(val)) {
div.innerHTML = "";
price.innerHTML = "";
} else {
switch (true) {
case (val <= 0):
{
div.innerHTML = "";
price.innerHTML = "";
break;
}
case (val >= qty1 && val < qty2):
{
div.innerHTML = val * price1;
price.innerHTML = price1;
break;
}
case (val >= qty2 && val < qty3):
{
div.innerHTML = val * price2;
price.innerHTML = price2;
break;
}
case (val >= qty3):
{
div.innerHTML = val * price3;
price.innerHTML = price3;
break;
}
}
}
}
<div>
Quantity — Price for each
</div>
<div>
<div>1 — $110</div>
<div>10 — $105</div>
<div>20 — $100</div>
</div>
<div>
Number of items:
<div>
<input id="txt" onblur="conversion(this.value)" onchange="conversion(this.value)" onkeypress="conversion(this.value)" onkeyup="conversion(this.value)" type="number">
</div>
</div>
<div>
Total:
<div id="div"></div>
</div>
<div>
Price for each:
<div id="price"></div>
</div>
How it can be properly implemented, taking into account the fact that the lines with the quantity and unit price can be from one to infinity (values are taken from the database)?
I think it is possible to record the price and quantity in data-atributes and parse it with JS. Like this:
...
<div data-quantity="10" data-price="105">
<span class="quantity">10</span>
<span class="price">105</span>
</div>
...
Thanks!
Using the data attribute is indeed a solution:
console.log(document.getElementById("test").dataset)
<div data-quantity="10" data-price="105" id="test">
<span class="quantity">10</span>
<span class="price">105</span>
</div>
It's not fully compatible with previous IE version though, so be careful with it.
I would however suggest that you look for a way of moving your calculations away from the DOM to speed up your calculations.
For instance, parsing the data to a JavaScript object and doing the calculations there would save you some DOM trips and thus speed:
console.clear();
//markup for product
function Product(name) {
return {
//Name of product
name : name,
//List of price ranges (populated later)
prices : [
],
//method for adding a price
newPrice : function newPrice(quantity, cost) {
//Push new price unto list
this.prices.push({
quantity : quantity,
cost : cost
});
//Sort list
this.prices = this.prices.sort(function (a, b) {
return a.quantity - b.quantity
});
},
//Get the price for a variable quantity of this product
get : function (quantity) {
//Loop through prices to find the most matching
var price = 0;
for (var i = 0; i < this.prices.length; i++) {
if (this.prices[i].quantity <= quantity) {
price = this.prices[i].cost;
} else {
break;
}
}
console.log('price per unit:', price, 'price for all', quantity, 'units:', price * quantity)
}
};
} //Make an instance
var myHotProduct = new Product('Fancy pants');
//Add some prices
myHotProduct.newPrice(0, 110);
myHotProduct.newPrice(10, 105);
myHotProduct.newPrice(20, 100);
//get some quantities
myHotProduct.get(0);
myHotProduct.get(1);
myHotProduct.get(9);
myHotProduct.get(10);
myHotProduct.get(19);
myHotProduct.get(20);
//Log everything we know about our product
console.log(myHotProduct);
Now you can get your prices as arrays and modify them outside of the limitations of data-.

Categories

Resources