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>
Related
I have a slider in my web page which start with 50 and i have to calculate it's price with other inputs
50 equals to 0€ when i increase the slider the value should be added to my total input like
(sliderValue - 50) * 0.35
When i increase there is no issue
But when i decrease the value is not removed...
How can i manage it? here is an example
var slider = document.getElementById("sliderHDD");
var output = document.getElementById("risultato");
var lastVal = 0
slider.oninput = function() {
var value = this.value
var prezzo = (value - 50) * 0.35;
var totale = document.getElementById("totale")
output.innerHTML = value;
if (lastVal < value) {
// increase
totale.value = parseInt(totale.value) + parseInt(prezzo)
} else {
// decrease
totale.value = parseInt(totale.value) - parseInt(prezzo)
}
lastVal = value
document.getElementById("tothdd").value = prezzo;
}
<tr>
<td><input style="width: 50%" step="10" type="range" min="50" max="500" value="50" class="slider" id="sliderHDD"></td>
<td><span id="risultato" align="left"></span></td>
<td></td>
<td><input type="text" id="tothdd" disabled="disabled" value="0.00" style="width:60px"></td>
<td>€</td>
</tr>
<br>
Total
<input type="text" id="totale" name="CostTotale" disabled="disabled" value="0" style="width:45px" class="text">
As you can see if i increase slider to X the value will be 42 and even in total will be 42, but then if i change it's value again the total will be not as it have to be
I am making a website that will generate a random number using JS. But it shows undefined for some reason. I DON'T want that to come. Here is my code.
var showRandomNumberDiv = document.getElementById("show-random-number");
var number1 = document.getElementById("number-1");
var number2 = document.getElementById("number-2");
var generate = document.getElementById("generate");
var newPara = document.createElement("p");
generate.addEventListener("click", function() {
numbers = [];
for (var i = 0; i > number1 && i < number2; i++) {
numbers.push(i);
}
newPara.innerHTML = numbers[Math.floor(Math.random() * numbers.length)];
showRandomNumberDiv.appendChild(newPara);
})
<h1>Hello, and welcome to Random generator!</h1>
<h2>Not only numbers, but letters too!</h2>
<p>If you want to enter a <span style="font-style:italic; font-weight: bold;">positive</span> number, see below.</p>
<!-- Generate a random number -->
<input type="text" placeholder="number 1" id="number-1">
<input type="text" placeholder="number 2" id="number-2">
<input type="button" value="Generate" id="generate">
<div id="show-random-number">
</div>
<script src="javascript.js"></script>
You did made a few mistakes in your code. Here's fixed version:
var showRandomNumberDiv = document.getElementById("show-random-number");
var number1 = document.getElementById("number-1");
var number2 = document.getElementById("number-2");
var generate = document.getElementById("generate");
var newPara = document.createElement("p");
showRandomNumberDiv.appendChild(newPara);
generate.addEventListener("click", function() {
var numbers = [];
for (var i = parseInt(number1.value); i < parseInt(number2.value); i++) {
numbers.push(i);
}
newPara.innerHTML = numbers[Math.floor(Math.random() * numbers.length)];
})
<h1>Hello, and welcome to Random generator!</h1>
<h2>Not only numbers, but letters too!</h2>
<p>If you want to enter a <span style="font-style:italic; font-weight: bold;">positive</span> number, see below.</p>
<!-- Generate a random number -->
<input type="text" placeholder="number 1" id="number-1">
<input type="text" placeholder="number 2" id="number-2">
<input type="button" value="Generate" id="generate">
<div id="show-random-number">
</div>
<script src="javascript.js"></script>
To get value from input you have to use input.value property. You can also use parseInt function to convert string value to number.
Also here's optimized version of the code.
var showRandomNumberDiv = document.getElementById("show-random-number");
var number1 = document.getElementById("number-1");
var number2 = document.getElementById("number-2");
var generate = document.getElementById("generate");
var newPara = document.createElement("p");
showRandomNumberDiv.appendChild(newPara);
generate.addEventListener("click", function() {
var min = parseInt(number1.value);
var max = parseInt(number2.value);
newPara.innerText = min + Math.round(Math.random() * (max - min));
})
<h1>Hello, and welcome to Random generator!</h1>
<h2>Not only numbers, but letters too!</h2>
<p>If you want to enter a <span style="font-style:italic; font-weight: bold;">positive</span> number, see below.</p>
<!-- Generate a random number -->
<input type="text" placeholder="number 1" id="number-1">
<input type="text" placeholder="number 2" id="number-2">
<input type="button" value="Generate" id="generate">
<div id="show-random-number">
</div>
<script src="javascript.js"></script>
You can multiply Math.random() with difference between maximum and minimum values and add the result to the minimum value to get a random number between minimum and maximum values.
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 am trying to make a tip calculator and the total variable returns a string because typeof bill is a string, why is it so, even though the text input box type is number?
output("bill entered is 1000 and no of person is 1):- string
150
150
1000150
document.querySelector('#persons').addEventListener('change', (findresult));
document.querySelector('#bill').addEventListener('change', (findresult));
document.querySelector('#percent').addEventListener('change', (findresult));
function findresult() {
var persons = document.getElementById('persons').value;
var bill = document.getElementById('bill').value;
var percent = document.getElementById('percent').value;
// console.log(persons);
console.log(typeof bill);
// console.log(percent);
var tip = (bill * percent) / 100;
var tip_person = tip / persons;
var total = bill + tip;
console.log(tip);
console.log(tip_person);
console.log(total);
}
<div class="container">
<h1>Tip calcuator</h1><br>
<div class="inputs">
<input type="number" class="inputfield" id="persons" placeholder="No of Persons"><br><br>
<input type="number" class="inputfield" id="bill" placeholder="Bill"><br><br>
<input type="number" class="inputfield" id="percent" placeholder="Tip%">
</div>
<br>
<div class="result">
<br>
<p>Tip Per Person :</p>
<p>TOTAL :</p>
</div>
</div>
Surround the bill, percent declaration values with parseFloat to allow for decimals while converting the value String to a Number.
var bill = parseFloat(document.getElementById('bill').value);
var percent = parseFloat(document.getElementById('percent').value);
You may allow decimals in the Number Input by using the step attribute and set it to 0.01. This will affect the values created when using the up,down button on the Input.
<input type="number" class="inputfield" id="bill" placeholder="Bill" step="0.01" >
document.querySelector('#persons').addEventListener('change', (findresult));
document.querySelector('#bill').addEventListener('change', (findresult));
document.querySelector('#percent').addEventListener('change', (findresult));
function findresult() {
var persons = document.getElementById('persons').value;
// Use parseFloat to allow for decimals
var bill = parseFloat(document.getElementById('bill').value);
var percent = parseFloat(document.getElementById('percent').value);
// console.log(persons);
console.log(typeof bill);
// console.log(percent);
var tip = (bill * percent) / 100;
var tip_person = tip / persons;
var total = bill + tip;
console.log(tip);
console.log(tip_person);
console.log(total);
}
<div class="container">
<h1>Tip calcuator</h1><br>
<div class="inputs">
<input type="number" class="inputfield" id="persons" placeholder="No of Persons"><br><br>
<!-- Allow cents to be allowed via the `step` attribute -->
<input type="number" class="inputfield" id="bill" placeholder="Bill" step="0.01" ><br><br>
<input type="number" class="inputfield" id="percent" placeholder="Tip%">
</div>
<br>
<div class="result">
<br>
<p>Tip Per Person :</p>
<p>TOTAL :</p>
</div>
</div>
User parseInt(), it will convert string into number.
function findresult() {
var persons = parseInt(document.getElementById('persons').value);
var bill = parseInt(document.getElementById('bill').value);
var percent = parseInt(document.getElementById('percent').value);
// console.log(persons);
console.log(bill);
// console.log(percent);
var tip = (bill * percent) / 100;
var tip_person = tip / persons;
var total = bill + tip;
console.log(tip);
console.log(tip_person);
console.log(total);
}
As mentioned by #Heretic Monkey, the input element has a property valueAsNumber and since the input type is always a number, we wouldn't have to worry about the parsing.
so we can use document.getElementById('persons').valueAsNumber
Also a few suggestions, it's always nice to break your code in smaller parts. Therefore separating the logic of fetching the input values and performing calculations separately will be a better approach and its not a good practice to call the DOM objects repeatedly.
For example, we can create a function for change event listener and read the event argument and update the necessary object of values,
document.querySelector('#persons').addEventListener('change', (update));
document.querySelector('#bill').addEventListener('change', (update));
document.querySelector('#percent').addEventListener('change', (update));
let values = {
persons: 0,
bill: 0,
percent: 0,
}
function update(event) {
values[event.currentTarget.id] = event.target.valueAsNumber;
findresult();
}
Finally, you can read the values as follows,
var persons = values["persons"];
var bill = values["bill"];
var percent = values["percent"];
So putting all together,
document.querySelector('#persons').addEventListener('change', (update));
document.querySelector('#bill').addEventListener('change', (update));
document.querySelector('#percent').addEventListener('change', (update));
let values = {
persons: 0,
bill: 0,
percent: 0,
}
function update(event) {
values[event.currentTarget.id] = event.target.valueAsNumber;
findresult();
}
function findresult() {
var persons = values["persons"];
var bill = values["bill"];
var percent = values["percent"];
var tip = (bill * percent) / 100;
var tip_person = tip / persons;
var total = bill + tip;
console.log(tip);
console.log(tip_person);
console.log(total);
}
<div class="container">
<h1>Tip calcuator</h1><br>
<div class="inputs">
<input type="number" class="inputfield" id="persons" placeholder="No of Persons" step="0.01"><br><br>
<input type="number" class="inputfield" id="bill" placeholder="Bill"><br><br>
<input type="number" class="inputfield" id="percent" placeholder="Tip%">
</div>
<br>
<div class="result">
<br>
<p>Tip Per Person :</p>
<p>TOTAL :</p>
</div>
</div>
Hope it helps.
I am trying to make an annual salary calculator using Javascript. Here is what I have so far:
<div id="fulldiv">
<p> Enter the following information to calculate your annual salary.</p>
<p>Hourly Wage:
<input type="text" name="wage" id="txt_wage" value ="0.00"/></p>
<p>Hours Per Week:
<input type="text" name="hours" id="txt_hours" value= "0.0"/> <br/><br/>
<button value="calculate" onclick="calcSalary()">Calculate</button></p>
<p id="results"></p>
<script type="text/javascript">
function calcSalary() {
var wage_element = document.getElementById('txt_wage');
var wage = parseInt(wage_element.value);
var hours_element = document.getElementById('txt_hours');
var hours = parseInt(hours_element.value);
var calculate = wage_element * hours_element * 52;
document.getElementByID('results').innerHTML = calculate;
}
</script>
</div>
When I click the button, nothing happens. Any thoughts?
Some typos in there. I have slightly rewritten and simplified the code to ensure the a) your calculations are on the value of the inputs and b) you are using labels to provide the text relative to the inputs - not p's.
function calcSalary() {
var wage = parseFloat(document.getElementById('txt_wage').value);
var hours = parseFloat(document.getElementById('txt_hours').value);
var calculate = wage * hours * 52;
document.getElementById('results').innerHTML = calculate;
}
<div id="fulldiv">
<p> Enter the following information to calculate your annual salary.</p>
<label for="txt_wage">Hourly Wage:</label>
<input type="text" name="wage" id="txt_wage" value ="0.00"/>
<label for="txt_hours">Hours Per Week:</label>
<input type="text" name="hours" id="txt_hours" value= "0.0"/>
<br/><br/>
<button value="calculate" onclick="calcSalary()">Calculate</button>
<p id="results"></p>
</div>
You code needs to be adjusted
var calculate = wage_element * hours_element * 52;
Should be changed into
var calculate = wage * hours * 52;
The problem is that you're calculating the element instead of the values.
#Gerard beat me to it by a minute, but here's the working code.
<div id="fulldiv">
<p> Enter the following information to calculate your annual salary.</p>
<p>Hourly Wage:
<input type="text" name="wage" id="txt_wage" value ="0.00"/></p>
<p>Hours Per Week:
<input type="text" name="hours" id="txt_hours" value= "0.0"/> <br/><br/>
<button value="calculate" onclick="calcSalary()">Calculate</button></p>
<p id="results"></p>
<script type="text/javascript">
function calcSalary() {
var wage_element = document.getElementById('txt_wage');
var wage = parseInt(wage_element.value);
var hours_element = document.getElementById('txt_hours');
var hours = parseInt(hours_element.value);
var calculate = wage * hours * 52;
document.getElementById('results').innerHTML = calculate;
}
</script>
</div>