Javascript problems: thisRate is not defined at HTMLInputElement.oninput - javascript

I tried to design a very simple calculator to calculate the ratio based on invest amount. The error message is:
thisRate is not defined at HTMLInputElement.oninput
Here is my code:
<!-- <form oninput="amout.value = (principal.valueAsNumber * rate.valueAsNumber) /100 " style = "font-family: Arial, Helvetica, sans-serif;"></form> -->
<fieldset>
<legend>calculate</legend>
<label for="principal">amout to invest:$</label>
<input type="number" min="0" max="2000" id="principal" value="10000">
<p><label for="rate">interest rate</label></p>
<input id="rate" type="range" min="0" max="20" value="0" oninput="thisRate.value = rate.value">
<output name="thisRate" for="rate">0</output><span>%</span>
<p>
interest received<strong>$<output name="amount">0</output></strong>
</p>
</fieldset>

Try This
var rate = document.getElementById("rate");
rate.oninput = ()=>{
let value = rate.value;
}
Or
var rate = document.getElementById("rate");
rate.onchange = ()=>{
let value = rate.value;
}

Related

How to reset JavaScript code when input value is changed?

I would like for the code to change its answer when I change the value of the input.
So let's say instead of 10, I would like it to tell me how much HP (health points) I will have at level 15. Is there any way I can do this? I'm not that experienced in Javascript.
So right now I coded it to default to 10 on all stats. My website tells me that at level 10, I have 895.4 hp. The only problem is that it won't stay at 15 when I try to press enter. It will just revert back to 10. Pretty much useless. Is there any way to keep that number 15 when I press enter?
var finalhp = 500;
let hpmultiplier = 1.06;
var hpvaluestring = document.querySelector('.hp').value;
var hpvalue = parseInt(hpvaluestring);
for (let i = 0; i < hpvalue; i++) {
var finalhp = finalhp * hpmultiplier
}
console.log(finalhp)
<form>
<div>
<input class="hp" id="amount" type="number" value="10" min="0" max="50" oninput="rangeInput.value=amount.value">
<input class="slider" id="rangeInput" type="range" value="10" min="0" max="50" oninput="amount.value=rangeInput.value">
</div>
</form>
Add a form submit event listener to the form element and prevent form submission there.
<form onsubmit="submitForm(event)">
<div>
<input class="hp" id="amount" type="number" value="10" min="0" max="50" oninput="rangeInput.value=amount.value">
<input class="slider" id="rangeInput" type="range" value="10" min="0" max="50" oninput="amount.value=rangeInput.value">
</div>
</form>
Add a submitForm function inside a script tag
function submitForm(event){
event.preventDefault();
var finalhp = 500;
let hpmultiplier = 1.06;
var hpvaluestring = document.querySelector('.hp').value;
var hpvalue = parseInt(hpvaluestring);
for (let i = 0; i < hpvalue; i++) {
var finalhp = finalhp * hpmultiplier
}
console.log(finalhp)
}
So mainly I'm just adding eventListeners to trigger the function calculateHP on input/slider value change. The function calculateHP contains the same logic that you shared. I did this so that the eventListeners can callback the function.
Try the following:
const input = document.querySelector('.hp')
const slider = document.querySelector('.slider')
slider.addEventListener('change', calculateHP)
input.addEventListener('change', calculateHP)
function calculateHP(){
let multiplier = 1.06
let level = Number(input.value)
let HP = 500
for(let i = 0; i<level; i++){
HP = HP * multiplier
}
return console.log(HP)
}
<div>
<label>Level: </label>
<input class="hp" id="amount" type="number" value="10" min="0" max="50" oninput="rangeInput.value=amount.value">
<input class="slider" id="rangeInput" type="range" value="10" min="0" max="50" oninput="amount.value=rangeInput.value">
</div>

Decimal / Thousand separator (dot and comma) in the calculation results Js and Input field

I'm trying to get separators for thousands, hundreds and decimals in the input field. For example: if I calculate 50 * 50 the result is 2500 while I would like to get 2.500,00
Otherwise: if I calculate 52,5 * 52,5 the result is 2756.25, while I would like to get 2.756,25
Below is the code I worked out helping me with stackoverflow posts https://jsfiddle.net/snake93/dyepq135/10/
I'm a fan and don't even know the basics of coding, so I was just trying to figure out how to implement the separators (dot and comma).
<label class="mts-label">Peso</label>
<input type="number" step="any" class="mts-field" maxlength="4" id="peso" name"peso1" placeholder="es: 70Kg"/>
<label class="mts-label">Altezza</label>
<input type="number" class="mts-field" maxlength="4" id="altezza" name"altezza1" placeholder="es: 170cm"/>
<label class="mts-label">BMR</label>
<input type="text" class="mts-field" id="bmruomo" name="bmruomo"
placeholder="0.000,0 Kcal" min="1" readonly/>
<button onclick="calculate()">Calcola</button>
<button id="reset" onclick="resetFields()">Reset</button>
calculate = function() {
var peso = document.getElementById('peso').value;
var altezza = document.getElementById('altezza').value;
var bmruomo = parseFloat(peso * altezza);
document.getElementById('bmruomo').value = bmruomo;
}
function resetFields(){
var inputArray = document.querySelectorAll('input');
inputArray.forEach(function (input){
input.value = "";
});
}
You can do that...
const
f_BMR = document.forms['f-BMR']
, num2strEUR = n =>
{
let str = n.toFixed(2).replace('.',',')
return [...str].reduce((r,c,i,a)=>
{
r += c
let p = (a.length - i)
if ((p%3)===1 && p>4) r += '.'
return r
},'')
}
f_BMR.onsubmit = e =>
{
e.preventDefault()
let bmr_val = (f_BMR.peso1.valueAsNumber * f_BMR.altezza1.valueAsNumber)
f_BMR.bmruomo.value = num2strEUR(bmr_val )
}
label,input, div {
display : block;
float : left;
clear : both;
}
label, div{
font-size : .7em;
font-weight : bold;
margin-top : .8em;
}
label:after {
content : ' :'
}
<form name="f-BMR">
<label>Peso</label>
<input name="peso1" type="number" step="any" placeholder="es: 70Kg" value="" required>
<label>Altezza</label>
<input name="altezza1" type="number" step="any" placeholder="es: 170cm"/ value="" required>
<label>BMR</label>
<input name="bmruomo" type="text" class="mts-field" placeholder="0.000,0 Kcal" value="" readonly>
<div>
<button type="submit">Calcola</button>
<button type="reset">Reset</button>
</div>
</form>

Calculate and display total as range slider moves

I'm trying to calculate and display the result of three ranger sliders. The equation I'm trying to display is:
KM driven per year * Avg KM/100L / Price of fuel
I've gotten the sliders to display each of their individual values but I'm not sure how to display the calculation.
View Codepen
<div>
<p>KM Driven per Year</p>
<p id="myAvgKM"></p>
<input type="range" min="0" max="300000" value="80000" step="1000" class="slider" id="kmdriven">
<p>On average, my truck gets around:</p>
<div class="response-container">
<p id="myAvgKPL"></p>
<p>L/100KM</p>
</div>
<input type="range" min="4" max="60" value="40" id="avgkm">
<p>Diesel prices are usually:</p>
<p id="price"></p>
<input type="range" min="0.000" max="3.000" value="1.308" step=".001" id="priceValue">
</div>
<div>
<p>In the first year alone, our services would save you:</p>
<p id="savings"></p>
</div>
function calculate () {
// Display KM Driven Slider
var kmPerYear = document.getElementById("kmdriven")
var kmOutput = document.getElementById("myAvgKM")
kmOutput.innerHTML = kmPerYear.value;
kmPerYear.oninput = function() {
kmOutput.innerHTML = this.value;
}
// Display Avg Mileage
var avgKM = document.getElementById("avgkm")
var avgKMOutput = document.getElementById("myAvgKPL")
avgKMOutput.innerHTML = avgKM.value;
avgKM.oninput = function() {
avgKMOutput.innerHTML = this.value;
}
//Display Avg Price
var avgPrice = document.getElementById("priceValue")
var priceOutput = document.getElementById("price")
priceOutput.innerHTML = avgPrice.value;
avgPrice.oninput = function () {
priceOutput.innerHTML = this.value;
}
// The Math!
document.getElementById("savings").innerHTML = "$ ";
}
You need map your function to onchange event as
<input onchange="calculate()" type="range" min="0" max="300000" value="80000" step="1000" class="slider" id="kmdriven">
Remove oninput, because your slider don't handle oninput change to onchange
Add formula for total saving
var total = (kmPerYear.value / 100) * (avgKM.value * 1.2) * avgPrice.value;
document.getElementById("savings").innerHTML = `$ ${total}`;
function calculate () {
// Display KM Driven Slider
var kmPerYear = document.getElementById("kmdriven");
var kmOutput = document.getElementById("myAvgKM")
kmOutput.innerHTML = kmPerYear.value;
// Display Avg Mileage
var avgKM = document.getElementById("avgkm")
var avgKMOutput = document.getElementById("myAvgKPL")
avgKMOutput.innerHTML = avgKM.value;
//Display Avg Price
var avgPrice = document.getElementById("priceValue")
var priceOutput = document.getElementById("price")
priceOutput.innerHTML = avgPrice.value;
// The Math!
var total = (kmPerYear.value / 100) * (avgKM.value * 1.2) * avgPrice.value;
document.getElementById("savings").innerHTML = `$ ${total}`;
}
.response-container {
display: flex;
}
<div>
<p>KM Driven per Year</p>
<p id="myAvgKM"></p>
<input onchange="calculate()" type="range" min="0" max="300000" value="80000" step="1000" class="slider" id="kmdriven">
<p>On average, my truck gets around:</p>
<div class="response-container">
<p id="myAvgKPL"></p>
<p>L/100KM</p>
</div>
<input onchange="calculate()" type="range" min="4" max="60" value="40" id="avgkm">
<p>Diesel prices are usually:</p>
<p id="price"></p>
<input onchange="calculate()" type="range" min="0.000" max="3.000" value="1.308" step=".001" id="priceValue">
</div>
<div>
<p>In the first year alone, our services would save you:</p>
<p id="savings"></p>
</div>
Add the window onload script at end of your javascript file
window.onload=calculate;
https://codepen.io/sanjayism/pen/vYNaoap

I cannot get the javaScript to do the function i am requesting it to do, in my case multiply two values by a hidden and then add a final value

I am so lost as to why this is not working properly, as it is on similar previous code. This is for field personnel, a cheat Sheet to simply enter values and get a fast answer (calculation). They enter the value of Num5/6/7 code multiplies 3 values one hidden then adds the last value together and upon click button the result is shown.
Here is my code (taken from copy/paste of a working conversion).
<div class="containerHydro">
<p>
<label >Fluid Column Length</label>
<input type="number" id="num5">
<label >Fluid Weight</label>
<input type="number" id="num6">
<label >Well Head Pressure</label>
<input type="number" id="num7">
<p>
<input type="button" value="Sum" onclick="calculate()"/>
</p>
<p id="total1"></p>
</div>
The Function also copy/paste of multiply two int then divide by hidden (which works BTW)
function calculate() {
var numFive = document.getElementById('num5').value;
var numSix = document.getElementById('num6').value;
var numSvn = document.getElementById('num7').value;
var total1 = parseInt(numFive) * parseInt(numSix) * 0.052 + parseInt('numSvn');
var p =document.getElementById('total1');
p.innerHTML += total1;
}
Here is the same idea which works fine-
Code-
<div class="container7">
<p>
<label id="H2S Percent">H2S Percentage</label>
<input id="num3" type="number" name="num3" placeholder="H2S Percent">
<label id="H2S Percent">WHP</label>
<input id="num4" type="number" name="num4"placeholder="Well Head Pressure" > <br>
</p>
<input type="button" value="H2S Partial Pressure" onclick="math()"/>
<p id="result"></p>
</div>
Function
function math() {
var numThree = document.getElementById('num3').value;
var numFour = document.getElementById('num4').value;
var result = parseInt(numThree) * parseInt(numFour) / 1000000;
var p = document.getElementById('result');
p.innerHTML += result;
}
function calculate() {
var numFive = document.getElementById('num5').value;
var numSix = document.getElementById('num6').value;
var numSvn = document.getElementById('num7').value;
var total1 = parseInt(numFive) * parseInt(numSix) * 0.052 + parseInt(numSvn);
var p = document.getElementById('total1');
p.innerHTML += total1;
}
input {
display: block;
}
<div class="containerHydro">
<p>
<label>Fluid Column Length</label>
<input type="number" id="num5">
<label>Fluid Weight</label>
<input type="number" id="num6">
<label>Well Head Pressure</label>
<input type="number" id="num7">
<p>
<input type="button" value="Sum" onclick="calculate()" />
</p>
<p id="total1"></p>
</div>

Writing a code in javascript with radio buttons and using if else loop to calculate simple and/or compound interest

I have been asked to write a code in javascript to show the results in the output boxes based on the input data, the form should like the one shown in the attached image:Interest Calculator
Till now, I have written down the following code; however I am unable to get the results in the output boxes. Could someone please help. Thanks in advance.
function calc() {
{
var p = document.getElementById("p").value;
var r = document.getElementById("r").value;
var t = document.getElementById("t").value;
var int = f.int.value;
}
if (int === "si") {
var sip = (p * r * t) / 100
var ta = p + sip
document.getElementById("i").innerHTML = sip;
document.getElementById("a").innerHTML = ta;
} else {
var cta = p * (Math.pow((1 + r / 100), t))
var cmp = cta - p
document.getElementById("i").innerHTML = cmp;
document.getElementById("a").innerHTML = cta;
}
}
<form name="f">
<h1> Interest Calculator </h1>
Principal = <input type="text" id="p" autofocus>
<br><br><br> Rate of Interest = <input type="text" id="r">
<br><br><br> Time (in years) = <input type="text" id="t">
<br><br>
<h1> Interest Type </h1>
<input type="radio" name="int" id="int" value="si"> Simple Interest
<input type="radio" name="int" id="int" value="ci"> Compound Interest
<br><br>
<hr noshade> Interest <input type="text" id="i">
<br><br> Amount <input type="text" id="a">
<br><br>
<input type="button" name="cal" value="Calculate" onclick="calc()">
<input type="reset" value="Reset">
</form>
innerHTML is used to retrieve or update the content/markup inside a DOM node that can have children. For input elements, you have to use value to get or set the value of the field.
function calc() {
{
var p = document.getElementById("p").value;
var r = document.getElementById("r").value;
var t = document.getElementById("t").value;
var int = f.int.value;
}
if (int === "si") {
console.log("simple interest");
var sip = (p * r * t) / 100
var ta = p + sip
document.getElementById("i").value = sip;
document.getElementById("a").value = ta;
} else {
console.log("compound interest");
var cta = p * (Math.pow((1 + r / 100), t))
var cmp = cta - p
document.getElementById("i").value = cmp;
document.getElementById("a").value = cta;
}
}
<form name="f">
<h1> Interest Calculator </h1>
Principal = <input type="text" id="p" autofocus>
<br><br><br> Rate of Interest = <input type="text" id="r">
<br><br><br> Time (in years) = <input type="text" id="t">
<br><br>
<h1> Interest Type </h1>
<input type="radio" name="int" id="int" value="si"> Simple Interest
<input type="radio" name="int" id="int" value="ci"> Compound Interest
<br><br>
<hr noshade> Interest <input type="text" id="i">
<br><br> Amount <input type="text" id="a">
<br><br>
<input type="button" name="cal" value="Calculate" onclick="calc()">
<input type="reset" value="Reset"><br><br><br>
</form>
Replace innerHTML with value. Because input values are updated using value attribute. Also
the braces here
{
var p = document.getElementById("p").value;
var r = document.getElementById("r").value;
var t = document.getElementById("t").value;
var int = f.int.value;
}
is not required.
function calc() {
var p = document.getElementById("p").value;
var r = document.getElementById("r").value;
var t = document.getElementById("t").value;
var int = f.int.value;
if (int === "si") {
var sip = (p * r * t) / 100
var ta = p + sip
document.getElementById("i").value = sip;
document.getElementById("a").value = ta;
} else {
var cta = p * (Math.pow((1 + r / 100), t))
var cmp = cta - p
document.getElementById("i").value = cmp;
document.getElementById("a").value = cta;
}
}
<form name="f">
<h1> Interest Calculator </h1>
Principal = <input type="text" id="p" autofocus>
<br><br><br> Rate of Interest = <input type="text" id="r">
<br><br><br> Time (in years) = <input type="text" id="t">
<br><br>
<h1> Interest Type </h1>
<input type="radio" name="int" id="int" value="si"> Simple Interest
<input type="radio" name="int" id="int" value="ci"> Compound Interest
<br><br>
<hr noshade> Interest <input type="text" id="i">
<br><br> Amount <input type="text" id="a">
<br><br>
<input type="button" name="cal" value="Calculate" onclick="calc()">
<input type="reset" value="Reset">
</form>

Categories

Resources