Re-selecting another value and clac but old result displays in JS - javascript

I'm studying calc. I'm having problem with re-selecting value and calc.
Here is my whole program
https://jsfiddle.net/diessses/c9ykmsf2/6/
When user select value then press submit. it works perfectly. However when user change such as 'cb_amount' , s_month and 's_year' Then click submit below code part displays OLD result. Other part result works fine. Could you teach me write code please?
// PAY_START_END_MONTH_FMT message
const PAY_START_END_MONTH_FMT = "If loan start Month is :start ,<br> Final loan paying will be :end ";
let s_month = document.getElementById(elementId.s_month).value;
if (s_month) {
let s_year = document.getElementById(elementId.s_year).value;
let date = new Date();
date.setMonth(s_month - 1);
date.setFullYear(s_year);
let startMonth = DateManager.formatDate(date, DateManager.getFormatString().YYYY_MM);
DateManager.addMonth(date, (years * 12) - 1);
let endMonth = DateManager.formatDate(date, DateManager.getFormatString().YYYY_MM);
document.getElementById("pay_start_end_month").innerHTML = PAY_START_END_MONTH_FMT.replace(":start", startMonth).replace(":end", endMonth);
}
// CB_SENTENCE_FMT message
const CB_SENTENCE_FMT = "Combined bonus amount will be :j_actual_cb_ttl. Paying times is :j_cbTimes . mothly paying is :j_monthly_bns_payment";
if (bSecondToLastTtl > 1) {
let j_actual_cb_ttl = ValueUtils.comma(bSecondToLastTtl);
let j_cbTimes = cbTimes;
let j_monthly_bns_payment = ValueUtils.comma(monthly_b);
document.getElementById("j_cb_sentence").innerHTML = CB_SENTENCE_FMT.replace(":j_actual_cb_ttl", j_actual_cb_ttl).replace(":j_cbTimes", j_cbTimes).replace(":j_monthly_bns_payment", j_monthly_bns_payment);
}

There are a lot of variables which you are have declaration as "const". Try changing those to "let". Read about it here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let. I have forked your code and tried, seems to be updating the data based on the new values.
Forked fiddle https://jsfiddle.net/b5g73x02/. Below is what I changed.
let cbTimes = years * 2; //
let diff = amount - downpayment;
let justDevideCbAmount = cb_amount / cbTimes;
let monthly_b = (Math.floor(justDevideCbAmount / 100) * 100);
let bSecondToLastTtl = monthly_b * cbTimes;
let paymentTimes = years * 12;
let interestMod = 10000 + (interest * 100);
let ttlWInterest = parseInt(((amount - downpayment) * interestMod )/ 10000);
let ttlWInterestNegativeCb = ttlWInterest - bSecondToLastTtl;
let jstDevideMonthly = ttlWInterestNegativeCb / paymentTimes;
let secondToLastMonthlyPayment = (Math.floor(jstDevideMonthly / 100) * 100);
let firstMonthlyPayment = ttlWInterestNegativeCb - (secondToLastMonthlyPayment * (paymentTimes - 1));
let jKinri = (interest / 100).toFixed(5);
let kinriFinal = ValueUtils.comma(parseInt(ttlWInterest - (amount - downpayment)));

Related

automatically compute base from the value of 2 inputs javascript

I'm starting to learn javascript, and I'm trying to make a calculator app to solve simple harmonic motion. and made a js code to solve automatically if there are values from the input fields.
similar mechanics on this website when you put values it automatically solves and you can delete the value to solve another one https://www.omnicalculator.com/physics/displacement
const mass_event = document.getElementById("mass");
const k_event = document.getElementById("spring-constant");
const period_event = document.getElementById("period");
mass_event.addEventListener("input", solve);
k_event.addEventListener("input", solve);
period_event.addEventListener("input", solve);
function solve () {
var mass = document.getElementById("mass").value;
var konstant = document.getElementById("spring-constant").value;
var time = document.getElementById("period").value;
m = Number(mass);
k = Number(konstant);
t = Number(time);
if (m && k != 0) {
period = (2 * Math.PI * Math.sqrt((m/k)));
document.getElementById("period").value = (period);
} else if (k && t != 0) {
mass_kg = (Math.pow(t, 2) * k) / (4 * Math.pow(Math.PI, 2));
document.getElementById("mass").value = (mass_kg);
} else if (m && t != 0) {
spring_constant = (4 * Math.pow(Math.PI, 2) * m) / (Math.pow(t, 2));
document.getElementById("spring-constant").value = (spring_constant);
}}
It works but when there are already 2 values you cant delete the input values to solve for another. I'm trying to do this so that i can remove the solve button

Override javascript

Drawing
when I hit the button on the top left on https://real-one.shifaul.repl.co/, nothing happens except the text changing to "to daily"
but what I want it is when I hit the button , it will change my javascript
the line that is running now (highlighted in blue) will stop working, and the line that is in the comment will start working, when I hit again it gets back to normal. it will go on forever
fetchTexts().then(([enQuotes, bnQuotes]) => {
const totalQuotes = enQuotes.length;
function getQuote() {
const pickedIndex = Math.floor(Math.random() * totalQuotes);
//const now = new Date(); const days = Math.floor(now/1000/60/60/24); const pickedIndex = days % totalQuotes
const newImageIndex = Math.floor(Math.random()*6); document.body.style.backgroundImage = `url(${newImageIndex}.jpg)`;
document.querySelector("#text1").innerText = enQuotes[pickedIndex];
document.querySelector("#text2").innerText = bnQuotes[pickedIndex];
}
getQuote(0);
setInterval(function() {
getQuote()
}, 24 * 60 * 60 * 1000);
});
full code: https://replit.com/join/xedbtvda-shifaul
I think that based on your code, you can do that:
var elem = document.getElementById("myButton1")
const now = new Date();
const days = Math.floor(now/1000/60/60/24);
const pickedIndex = elem.value === 'On refresh'
? Math.floor(Math.random() * totalQuotes)
: days % totalQuotes
This worked for me (I tested by lowering the value of getQuotes interval)

Is there a way to show numbers better formatted in javascript? (with commas etc..)

If I use toLocaleString at the end of each line, I get 1 number formatted, and all other numbers get value NaN.
let cta = document.getElementById('cnt');
cta.addEventListener('click', function(e) {
let deviza = document.getElementById('deviza').value;
let kurs = document.getElementById('kurs').value;
let prihod = document.getElementById('prihod').value = (deviza * kurs).toFixed(2);
let trosak = document.getElementById('trosak').value = (prihod * .2).toFixed(2);
let osnovica = document.getElementById('osnovica').value = (parseFloat(prihod) - parseFloat(trosak)).toFixed(2);
let porez = document.getElementById('porez').value = (osnovica * .2).toFixed(2);
let pio = document.getElementById('pio').value = (osnovica * .255).toFixed(2);
let zdrav = document.getElementById('zdrav').value = (osnovica * .103).toFixed(2);
let totalPorez = document.getElementById('totalPorez').value = (parseFloat(porez) + parseFloat(pio) + parseFloat(zdrav)).toFixed(2);
let netoPrihod = document.getElementById('netoPrihod').value = (parseFloat(prihod) - parseFloat(totalPorez)).toFixed(2);
})
Try using Numeral.js, library that is rich in number formatting options, so you don't have to reinvent the wheel :)

interchanging and manipulating two form input values

I've created a calculator that requires a value in either months or years in order to perform a calculation. The calculator works with one exception: It is required that the two input fields update based on the value of each other. here's an example of the behavior I am attempting to recreate:
https://www.bankrate.com/calculators/mortgages/loan-calculator.aspx
I apologize in advance if the following example reads poorly, but here it goes:
If a user enters 72 'months', the 'years' input will divide months by 12 and display the result. After doing a little tooling around, I found that using [a, b] = [b*12, a/12] gets me halfway there. The problem I'm running into is that once values have been entered, the value of the most recently updated input is updated with the previous value (including the calculation). For example, User enters 60 months > years is populated with the value of 5 > user changes months to a value of 72 > years is populated with a value of 6 > months is automatically populated with a value of 60 (years remains at a value of 6)
Here's the JS:
const loan = () => {
let principal = document.getElementById('principal')
let interestRate = document.getElementById('interestRate')
let terms = document.getElementById('terms')
let termsInYears = document.getElementById('termsInYears')
let payment = document.getElementById('payment')
let total = document.getElementById('total')
let totalInterest = document.getElementById('totalInterest')
let closingCosts = document.getElementById('closingCosts')
let netAfterFees = document.getElementById('netAfterFees')
let totalFeesAndInterest = document.getElementById('totalFeesAndInterest')
let trueCost = document.getElementById('trueCost')
let amount = parseFloat(principal.value)
let interest = parseFloat(interestRate.value) / 100 / 12
let payments = parseFloat(terms.value)
let fees = parseFloat(closingCosts.value)
if(!fees) {
closingCosts.value = 0
}
[terms.value, termsInYears.value] = [termsInYears.value*12, terms.value/12]
let x = Math.pow(1 + interest, payments)
let monthly = (amount * x * interest) / (x-1)
let totalPay = (monthly * payments)
if (isFinite(monthly) && payment) {
payment.innerHTML = monthly.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,')
netAfterFees.innerHTML = (amount - fees).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,')
total.innerHTML = (totalPay).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,')
totalInterest.innerHTML = ((monthly * payments) - amount).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,')
totalFeesAndInterest.innerHTML = (totalPay - amount + fees).toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,')
trueCost.innerHTML = (((totalPay - amount + fees) / amount)*100).toFixed(2)
} else {
payment.innerHTML = '0'
netAfterFees.innerHTML = '0'
total.innerHTML = '0'
totalInterest.innerHTML = '0'
totalFeesAndInterest.innerHTML = '0'
trueCost.innerHTML = '0'
}
}
I can't speak on the quality of the working calculator given my experience level. However, it does work. I'm just having one heck of a time getting past this [likely silly] input exchange.
Any help would be greatly appreciated!
I ended up solving this issue using querySelector and then adding an event listener for each input:
document.querySelector('#terms').addEventListener('input', (e) => {
termsInYears.value = e.target.value / 12
})
document.querySelector('#termsInYears').addEventListener('input', (e) => {
terms.value = e.target.value * 12
})

How can I get the level by given experience?

I have a formula that calculates the experience based on a certain level and another that calculates the level based on the given experience.
But the second function does not return the expected value.
const levels = 40;
const xp_for_first_level = 1000;
const xp_for_last_level = 1000000;
const getExperience = level => {
const B = Math.log(xp_for_last_level / xp_for_first_level) / (levels - 1);
const A = xp_for_first_level / (Math.exp(B) - 1.0);
const old_xp = Math.round(A * Math.exp(B * (level - 1)));
const new_xp = Math.round(A * Math.exp(B * level));
return new_xp - old_xp;
};
const getLevel = experience => {
const B = Math.log(xp_for_last_level / xp_for_first_level) / (levels - 1);
const A = xp_for_first_level / (Math.exp(B) - 1.0);
return Math.ceil(Math.log(experience / A) / B);
};
console.log(getLevel(xp_for_first_level)); // -9
console.log(getLevel(xp_for_last_level)); // 30
Expected result 1 and 40, but returns -9 and 30.
Can anyone help?
Anyone enlighten me, please?
I think the formula should change, i tried with this and it given correct return.
const getLevel = experience => {
const B = Math.log(xp_for_last_level / xp_for_first_level) / (levels + 1);
const A = xp_for_first_level - 1;
return Math.ceil(Math.log(experience / A) / B);
};

Categories

Resources