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
Related
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>
I have three types for tickets. Children - cost 8$, retirees - cost 10$ and adults - cost 12$ and i have 3 input numbers and i want when someone of these three input change to calculate and print in html total price
This is my html
children<input type="number" id="children" name="children" min="0" max="20" value="0" onchange="myScript">
adults<input type="number" id="adults" name="adults" min="0" max="20" value="0" onchange="myScript">
retirees<input type="number" id="retirees" name="retirees" min="0" max="20" value="0" >
This is my js
function totalPrice(){
var total = 0
var children = document.getElementsByName('children');
var children = document.getElementsByName('adults');
var children = document.getElementsByName('retirees');
total = (parseInt(children) * 8) + (parseInt(adults) * 12) + (parseInt(retirees) * 10);
Here i dont know how to print in html total price
I want to look something like that
One possible way is to place a div for displaying Total in html
<div id="total"></div>
then attach an "eventListener" for change to each input field to trigger the calculation
document.querySelectorAll("input").forEach(el => {
el.addEventListener("change", () => {
totalPrice();
});
});
then update the value in html with:
totalDiv.innerHTML = `<h3>Total: ${total}$</h3>`;
Working Stackblitz
Given a div below the <inputs>, in the form of <div id="price"></div>
You could set the price this way:
let price_div = document.querySelector("#price")
// Apply whatever formatting to the price you want.
price_div.innerHTML = total
As these are input fields you can just use their value
function totalPrice(){
var total = 0
var children = document.getElementsByName('children');
var adults = document.getElementsByName('adults');
var retirees = document.getElementsByName('retirees');
total = (parseInt(children.value) * 8) + (parseInt(adults.value) * 12) + (parseInt(retirees.value) * 10);
function totalPrice(){
var total = 0
var children = document.getElementsByName('children')[0].value;
var adults = document.getElementsByName('adults')[0].value;
var retirees = document.getElementsByName('retirees')[0].value;
total = (children * 8) + (adults * 12) + (retirees * 10);
console.log(total);
document.getElementById('totalPrice').textContent=total;
}
children <input type="number" id="children" name="children" min="0" max="20" value="0" onKeyUp="totalPrice()">
adults <input type="number" id="adults" name="adults" min="0" max="20" value="0" onKeyUp="totalPrice()">
retirees <input type="number" id="retirees" name="retirees" min="0" max="20" value="0" onKeyUp="totalPrice()">
<div id="totalPrice" style="color:red"></div>
I'm trying to make a loan calculator by making two range slider interact with one another then show a the monthly payments in a label, these are the two requirements:
Only show 5 values on the "Month" range slider: 12,18,24,30,36 months (solved by Alexander Solonik)
Calculate an interest of 75%. (solved myself)
ok the code has evolved this way,:
<!--first range slider: money needed to borrow-->
<script language="JavaScript">
function showpay() {
var princ = document.calc.loan.value;
var term = document.calc.months.value;
var intr = (75 / 1200)*1.16; /*must include taxes, depending on your country, in my case is 16%*/
var auxterm = 0;
switch(term){
case '1': auxterm = 12; break;
case '2': auxterm = 18; break;
case '3': auxterm = 24; break;
case '4': auxterm = 30; break;
case '5': auxterm = 36; break;
}
document.calc.pay.value = Math.round((princ * 1000) * intr / (1 - (Math.pow(1/(1 + intr), auxterm))));
// payment = principle * monthly interest/(1 - (1/(1+MonthlyInterest)*Months))
}
</script>
<center>
<form name=calc method=POST>
<table width=60% border=0>
<h1>¿How much money do you need?</h1>
<p>Borrow from $2,000 to $80,000</p><br>
<div>
<input name="loan" type="range" min="2" max="80" value="2" class="slider" id="myRange" style="color: black;">
<p><br><strong>$ <span id="demo"></span>,000</strong></p>
</div>
<script>
var slider = document.getElementById("myRange");
var output = document.getElementById("demo");
output.innerHTML = slider.value;
slider.oninput = function() { output.innerHTML = this.value; }
</script>
<h1>In how many months would you like to pay?</h1>
<p>from 12 to 36 months.</p><br>
<div>
<input name="months" type="range" min="1" max="5" value="0" class="slider" id="input" style="color: black;">
<strong><p><span id="result"></span> months</p></strong>
</div>
<script>
var result = document.getElementById('result'), input = document.getElementById('input')
var arr = [12,18,24,30,36]
input.oninput = function() { result.innerHTML = arr[this.value - 1] }
input.oninput()
</script>
<!--<tr>
<p>$ <span oninput="showpay()" value=Calculate></span></p>
</tr>-->
<tr>
Monthly Payment
<input type=text name=pay size=10>
</tr>
<input type=button onClick='showpay()' value=Calculate><!-- oninput="showpay()"-->
</table>
</form>
</center>
It is basicly complete, however the interest calculation is wrong, on the month slider it takes the values: 1,2,3,4,5 as that is the value of the slider, i need it to take the value of the arr = [12,18,24,30,36] instead, any idea how to do this?
ok this is now solved, may this be of help to some school projet or an actual loan calculator. :)
For only specific values o be selected in the range slider you can do something like this
var result = document.getElementById('result'),
input = document.getElementById('input')
var arr = [12,18,24,30,36]
input.oninput = function() {
result.innerHTML = arr[this.value - 1]
}
input.oninput()
<input type="range" min="1" max="5" id="input" value="0">
<div id="result">
</div>
You have a typo, its slider not lider.
Change on line 22 to
slider.oninput = function() { output.innerHTML = this.value; }
And the value is not visible because you applied CSS color value white in p tag. Also change that to
<p class="subtitulo" style="color: black;"><br><strong><span id="demo2"></span> months</strong></p>
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;
}
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>