BMI Calculation Program - javascript

I have created an application to calculate BMI. Basically, here is how I'd like the application to work and wrote below so far:
You just enter your height in inches and enter weight in pounds.
The application will calculate your BMI, then tell you whether you are underweight, normal, obese, or overweight.
In case you enter a non-positive value for either height or weight, the program will show you an error message that "Invalid input. Enter a positive number.", and it will highlight the boxes that you need to fix/enter a valid value.
I have encountered 2 problems.
I can get the program to show the BMI result, but currently I don't know how to write to get the program to show whether the user is underweight, normal, obese, or overweight.
If BMI < 18.5 then underweight, BMI >= 18.5 and <=24.99 then normal, BMI > 25 and <=29.99 then obese, and BMI > 30 then overweight.
I would like to show the error (that tells user to enter positive values, not missing or negative values) as messages below the "Calculate BMI" button, not as an alert like "This page says - Invalid input for weight, enter a non-negative number." In other words, I would like to keep the same message but not using "alert" method.
How may I fix these problems please? I have attached both my HTML and my CSS codes below.
Thank you so much!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>BMI Calculation</title>
<link rel="stylesheet" href="bmi.css">
</head>
<body>
<main>
<h2>Body Mass Index Calculation Application</h2>
<label for="boxHeight">Enter height in inches:</label>
<input type='text' id='boxHeight'/><br>
<label for="boxWeight">Enter weight in pounds:</label>
<input type='text' id='boxWeight'/><br>
<label> </label>
<input type="button" id="calculate" value="Calculate">
<div class="results"></div>
</main>
<script>
var processEntries = function() {
var heightInputBox = document.getElementById("boxHeight");
var weightInputBox = document.getElementById("boxWeight");
var outputBMI = document.querySelectorAll("div.results");
outputBMI[0].textContent = "";
heightInputBox.className = "";
weightInputBox.className = "";
console.log(heightInputBox.getAttribute('class'));
///get user input from input box "boxHeight" by using value property,
//which return user input as a string
//step1.1:get height input and convert height to a number
var height = heightInputBox.value;
height = parseFloat(height);
//step1.2:get weight input and convert weight to a number
var weight = weightInputBox.value;
weight = parseFloat(weight);
var valid = true;
if (isNaN(height)||height <0) {
alert("Invalid input for height, enter a non-negative number.");
heightInputBox.className = "error";
valid = false;
}
if (isNaN(weight)||weight <0) {
alert("Invalid input for weight, enter a non-negative number.");
weightInputBox.setAttribute('class', "error");
valid = false;
}
if (valid) //calculate BMI
{
outputBMI[0].textContent ="Your BMI is: " + (703 * weight / (height*height)).toFixed(1);
if (outputBMI[0]<18.5) outputBMI[0].textContent = "Your BMI indicates that you are underweight.";
if (outputBMI[0]>=18.5 && outputBMI[0]<=24.99) document.getElementById("result").value = "Normal";
if (outputBMI[0]>=25 && outputBMI[0]<=29.99) document.getElementById("result").value = "Obese";
if (outputBMI[0]>30) document.getElementById("result").value = "Overweight";
}
};
//add js code here to handler click event, and make the height input box be focused after the page is opened in web browser
document.getElementById('calculate').onclick = processEntries;
</script>
</body>
</html>
Here is my CSS code also, if you need it:
article, aside, figure, footer, header, main, nav, section {
display: block;
}
body {
font-family: Arial, Helvetica, sans-serif;
background: url('BMI.jpg') center center fixed;
margin: 0 auto;
width: 600px;
border: 3px solid blue;
}
html {
background-color: #eee;
}
main {
padding: 0 2em 1em;
margin: 2em;
background-color: white;
}
h2 {
color: blue;
}
label {
float: left;
width: 12em;
text-align: right;
padding-bottom: .5em;
}
div {
width: 24em;
text-align: left;
padding-bottom: .5em;
font-size: 20px;
}
input {
margin-left: 1em;
margin-bottom: .5em;
}
input.error {
background-color: #FFFF00;
border: 2px solid #fe9772;
}

There's a lot to rework on your code. But the bottom line is that you need to remember that a classSelector (in your case results) always return an array. Switch to an Id if you're using an unique dom
var processEntries = function() {
var heightInputBox = document.getElementById("boxHeight");
var weightInputBox = document.getElementById("boxWeight");
var resultElm = document.getElementById("result");
resultElm.textContent = "";
heightInputBox.className = "";
weightInputBox.className = "";
console.log(heightInputBox.getAttribute('class'));
///get user input from input box "boxHeight" by using value property,
//which return user input as a string
//step1.1:get height input and convert height to a number
var height = heightInputBox.value;
height = parseFloat(height);
//step1.2:get weight input and convert weight to a number
var weight = weightInputBox.value;
weight = parseFloat(weight);
var valid = true;
if (isNaN(height)||height <0) {
alert("Invalid input for height, enter a non-negative number.");
heightInputBox.className = "error";
valid = false;
}
if (isNaN(weight)||weight <0) {
alert("Invalid input for weight, enter a non-negative number.");
weightInputBox.setAttribute('class', "error");
valid = false;
}
var bmi = 703 * weight / (height** 2)
if (valid) //calculate BMI
{
resultElm.textContent ="Your BMI is: " + (bmi).toFixed(1);
if (bmi<18.5) resultElm.textContent += " Your BMI indicates that you are underweight.";
if (bmi>=18.5 && bmi<=25) resultElm.textContent += " Your BMI indicates that you are Normal.";
if (bmi>=25 && bmi<=30)resultElm.textContent += " Your BMI indicates that you are Obese.";
if (bmi>30) resultElm.textContent += " Your BMI indicates that you are Overweight";
}
};
//add js code here to handler click event, and make the height input box be focused after the page is opened in web browser
document.getElementById('calculate').onclick = processEntries;
article, aside, figure, footer, header, main, nav, section {
display: block;
}
body {
font-family: Arial, Helvetica, sans-serif;
background: url('BMI.jpg') center center fixed;
margin: 0 auto;
width: 600px;
border: 3px solid blue;
}
html {
background-color: #eee;
}
main {
padding: 0 2em 1em;
margin: 2em;
background-color: white;
}
h2 {
color: blue;
}
label {
float: left;
width: 12em;
text-align: right;
padding-bottom: .5em;
}
div {
width: 24em;
text-align: left;
padding-bottom: .5em;
font-size: 20px;
}
input {
margin-left: 1em;
margin-bottom: .5em;
}
input.error {
background-color: #FFFF00;
border: 2px solid #fe9772;
}
<main>
<h2>Body Mass Index Calculation Application</h2>
<label for="boxHeight">Enter height in inches:</label>
<input type='text' id='boxHeight'/><br>
<label for="boxWeight">Enter weight in pounds:</label>
<input type='text' id='boxWeight'/><br>
<label> </label>
<input type="button" id="calculate" value="Calculate">
<div id="result"></div>
</main>

After a while, I have edited my code several times and this is a version that I think is worth sharing. I know that there are still quite some edits to do - but here it is:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>BMI Calculation</title>
<link rel="stylesheet" href="bmi.css">
</head>
<body>
<main>
<h2>Body Mass Index Calculation Application</h2>
<label for="boxHeight">Enter height in inches:</label>
<input type='text' id='boxHeight'/><br>
<label for="boxWeight">Enter weight in pounds:</label>
<input type='text' id='boxWeight'/><br>
<label> </label>
<input type="button" id="calculate" value="Calculate">
<div class="results"></div>
</main>
<script>
var processEntries = function() {
var heightInputBox = document.getElementById("boxHeight");
var weightInputBox = document.getElementById("boxWeight");
var outputBMI = document.querySelectorAll("div.results");
outputBMI[0].textContent = "";
heightInputBox.className = "";
weightInputBox.className = "";
console.log(heightInputBox.getAttribute('class'));
var height = heightInputBox.value;
height = parseFloat(height);
var weight = weightInputBox.value;
weight = parseFloat(weight);
var valid = true;
if (isNaN(height)||height <0 || height != parseInt(height, 10)) {
outputBMI[0].textContent +=" Invalid input for height, enter a non-negative number.";
heightInputBox.className = "error";
valid = false;
}
if (isNaN(weight)||weight <0 || weight != parseInt(weight, 10)) {
outputBMI[0].textContent +=" Invalid input for weight, enter a non-negative number.";
weightInputBox.setAttribute('class', "error");
valid = false;
}
if (valid)
{
outputBMI[0].textContent ="Your BMI is: " + (703 * weight / (height*height)).toFixed(1);
//This is just for my trial and learning process. =)
var bmi = (703 * weight / (height*height)).toFixed(1);
if (bmi<18.5) outputBMI[0].textContent += " Your BMI indicates that you are underweight.";
if (bmi>=18.5 && bmi<=25) outputBMI[0].textContent += "Your BMI indicates that you are normal.";
if (bmi>25 && bmi<=30) outputBMI[0].textContent += "Your BMI indicates that you are obsese.";
if (bmi>30) outputBMI[0].textContent += "Your BMI indicates that you are overweight.";
}
};
//handler button click event
document.getElementById('calculate').onclick = processEntries;
</script>
</body>
</html>

I know this question already has a good and valid answer.
The following is simply the result of me playing around with the fiddle, trying to shorten it and make it more "responsive".
I removed the calculate button and use eval() now to tolerantly convert and calculate the input fields' values.
const qs=s=>document.querySelector(s);
evl=s=>{var v='', el=qs(s);
try{v=eval(el.value)||''} catch(er){v=''}
el.nextElementSibling.innerText=(v?'='+v.toFixed(2):v);
return v
}
var scale=[[18.5,"underweight"],
[25,"normal"],[30,"obese"],
[31,"seriously overweight"]];
qs("body").addEventListener("keyup",ev=>{if(ev.target.type!='text') return;
var txt, height=evl("#boxHeight"), weight=evl("#boxWeight");
if (height>0 && weight>0){
BMI=703*weight/(height*height);
scale.every(sc=>(txt=sc[1],BMI>sc[0]));
txt='Your BMI of '+BMI.toFixed(1)+" indicates<br>that you are "+txt+".";
} else txt='';
qs("#result").innerHTML=txt
});
body {
font-family: Arial, Helvetica, sans-serif;
background: url('BMI.jpg') center center fixed;
margin: 0 auto;
width: 600px;
border: 3px solid blue;
}
html {
background-color: #eee;
}
main {
padding: 0 2em 1em;
margin: 2em;
background-color: white;
}
h2 {
color: blue;
}
label {
float: left;
width: 12em;
text-align: right;
padding-bottom: .5em;
}
div {
width: 24em;
text-align: left;
padding-bottom: .5em;
font-size: 20px;
}
input {
margin-left: 1em;
margin-bottom: .5em;
}
span {margin-left:20px;
font-size:1.5ex;}
<main>
<h2>Body Mass Index Calculation Application</h2>
<label for="boxHeight">Enter height in inches:</label>
<input type='text' id='boxHeight' placeholder="value or formula"/><span id="one"></span><br>
<label for="boxWeight">Enter weight in pounds:</label>
<input type='text' id='boxWeight' placeholder="value or formula"/><span id="two"></span><br>
<div id="result"></div>
</main>

Related

Having issues with passing arguments through function (Javascript)

I'm creating a function using Javascript where the user puts in two integers, and the function will output the smaller of the two integers:
function minimum(num1, num2) {
var num1 = document.getElementById('input1').value;
var num2 = document.getElementById('input2').value;
if(num1 < num2){
document.getElementById('para').innerHTML = num1;
}
else if (num2 < num1){
document.getElementById('para').innerHTML = num2;
}
else {
document.getElementById('para').innerHTML = "There was something weird about your numbers. Please try again.";
}
}
body{
background-color: #A9927D ;
max-width: 900px;
min-width: 600px;
}
h1{
color: #F2F4F3;
text-align: center;
font-size: 45px;
}
h3 {
font-size: 20px;
color: #F2F4F3;
}
.container{
text-align: center;
}
.button-container {
padding: 50px;
}
.bttn{
height: 50px;
border-radius: 40px;
font-size: 20px;
font-family:'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
padding: 30px;
background-color: #5E503F;
box-shadow: 2px 2px 2px 2px #312A21;
color: #F2F4F3;
}
.bttn:hover {
background-color: #251F18;
}
.bttn:active {
box-shadow: 0 1px 0px #251F18;
}
.npt {
height: 40px;
width: 100px;
}
#para{
text-align: center;
margin: auto;
width: 40%;
height: 100px;
border: 1px solid #6E5E49;
background-color: #9C8568;
font-size: 20px;
color:#F2F4F3;
}
<div class="container">
<h1>Find the Minimum</h1>
<h3>by Solange Wright</h2>
<div class = "button-container">
<input class = "npt" type="number" id = "input1"><br><br>
<input class = "npt" type="number" id = "input2"><br><br><br><br>
<span class = bttn onclick = "minimum(num1, num2)">Find</span>
</div>
<p id="para"></p>
</div>
For some reason, I'm getting an error like this:
How do I define num1? Is it an issue with data types? Does the .value method in Javascript do type coercion, or is there another additional step to make sure the two values are integers?
You need to pass the id of the input.
Replace
<span class="bttn" onclick="minimum(num1, num2)">Find</span>
with
<span class"bttn" onclick="minimum('input1', 'input2')">Find</span>
It's generally not a good idea to use inline event handlers. You can use one handler for the document and use a generic handler (event delegation). Doing so gives you the possibility to use everything you need within the handler function.
Furthermore, the submitted values have to be checked (do both input have values?) and converted to Number (retrieved input values are always strings).
Finally you can use Math to determine the smallest number in an array of numbers.
This brings us to (removed stuff to present a minimum reproducable example):
document.addEventListener("click", getMinimalValue);
// ^ add a click listener method document wide
function getMinimalValue(evt) {
if (evt.target.id === "findSmallest") {
const numbers = [
document.querySelector("#input1").value || NaN,
document.querySelector("#input2").value || NaN
]
// ^ aggregate values into array (assign NaN if no value)
.map(Number)
// ^ convert values to Number (NaN will remain NaN)
.filter(n => !isNaN(n));
// ^ filter numbers only
document.querySelector("#para").textContent =
numbers.length < 2 ?
// ^ if not both entered values are numbers
// [numbers] array length is < 2
"You did not enter two numeric values" :
`Minimum of ${numbers.join(' and ')}: ${Math.min.apply(null, numbers)}`;
}
}
.npt {
width: 50px;
margin-bottom: 5px;
}
<input class="npt" type="number" id="input1">
<input class="npt" type="number" id="input2">
<span id="para"></span>
<br><button id="findSmallest">Find Minimum</button>
Remove the minimum parameters in the JS code (and also check if num1 and num2 are numbers)
function minimum() {
var num1 = document.getElementById('input1').value;
var num2 = document.getElementById('input2').value;
if (Number.isNaN(num1) || Number.isNaN(num2)){
document.getElementById('para').innerHTML = "please insert valid numbers";
return;
}
if(num1 < num2){
document.getElementById('para').innerHTML = num1;
}
else if (num2 < num1){
document.getElementById('para').innerHTML = num2;
}
else {
document.getElementById('para').innerHTML = "There was something weird about your numbers. Please try again.";
}
}
Refactor the button onclick not to pass paramters.
<div class="container">
<h1>Find the Minimum</h1>
<h3>by Solange Wright</h2>
<div class = "button-container">
<input class = "npt" type="number" id = "input1"><br><br>
<input class = "npt" type="number" id = "input2"><br><br><br><br>
<span class = "bttn" onclick = "minimum()">Find</span>
</div>
<p id="para"></p>
</div>

How to change the font color of an user input value (prompt) in JavaScript?

How can I change the color of the value of the variable number (nb)? How can I change the font color of an user input value (prompt) in JavaScript?
<html>
<head>
<style>
#block{
color: white;
width: 300px;
height: 60px;
background-color: #2b2e2e;
text-align: center;
padding-top: 30px;
}
</style>
</head>
<body>
<div id="block">
</div>
<script>
window.onload = function printNumber(){
var unBlock = document.getElementById("block");
var nb = Number(prompt("Saisir un nombre: "));
if(nb == null || nb == ""){
unBlock.innerHTML = "No input number.";
}else{
unBlock.innerHTML = "Your input number is "+nb;
}
}
</script>
</body>
</html>
The code below illustrates two ways.
By creating a span with colored as its class, it turns it blue.
Subsequently, in my code, I'm overriding that by turning it red using javascript.
Either of those methods will work, but you only need one, not both. I used both just for illustration of your options.
window.onload = function printNumber() {
var unBlock = document.getElementById("block");
var nb = Number(prompt("Saisir un nombre: "));
if (nb == null || nb == "") {
unBlock.innerHTML = "No input number.";
} else {
unBlock.innerHTML = `Your input number is <span class='colored'>${nb}</span>`;
//the next line will select your span and override blue with red.
document.querySelector("span.colored").style.color = 'red';
}
}
#block {
color: white;
width: 300px;
height: 60px;
background-color: #2b2e2e;
text-align: center;
padding-top: 30px;
}
span.colored {
color: blue;
}
<div id="block">
</div>

Changing CSS style of a class with Javascript

I'm new to javascript and I'm coding a temperiture converter. The program is basically done except im trying to make it so that the color of the text changes depending on the value of the temperiture. Eg: its 3 Degrees celcius so the text is blue to show that it's cold.
I added a class called temperiture to all of the I want the colour to change on. I've tried document.getElementByClassName aswell as document.QuerySelector.
The class 'temperature' has not been touched in the CSS file
This error is shown twice for the same line:
//Creating the funtion to convert celcius
function celciusConverter() {
const cTemp = parseFloat(celciusInput.value);
//Working out celcius to farenheight
const fTemp = (cTemp * (9/5) + 32);
//Working out celcius to kelvin
const kTemp = (cTemp + 273.15);
//Displaying the temperiture in all formats
farenheightInput.value = fTemp;
kelvinInput.value = kTemp;
if (cTemp < 15){
document.getElementsByClassName('#temperature')[0].style.color='black';
}
}
//Refreshing the screen when a number is put in
celciusInput.addEventListener('input', celciusConverter);
#import url('https://fonts.googleapis.com/css?family=Oswald&display=swap');
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
body{
background: black;
}
div{
height: 33.333vh;
}
#Farenheight{
border-top: 5px;
border-bottom: 5px;
}
input[type=number]{
outline: none;
width: 100%;
height 100%;
background: black;
color: white;
font-size: 6em;
text-align: centre;
border: 0;
font-family: Oswald, sans-serif;
}
<body>
<div id="celcius" class"temperature">
<input type="number" placeholder="Celcius. . .">
</div>
<div id="farenheight" class"temperature">
<input type="number" placeholder="Farenheight. . .">
</div>
<div id="kelvin" class"temperature">
<input type="number" placeholder="Kelvin. . .">
</div>
</body>
Uncaught TypeError: Cannot read property 'style' of undefined
at HTMLInputElement.celciusConverter
The reason why the color change was not working is because your temperature class was on the divs wrapping the inputs, and form items (inputs/textarea/etc) don't inherit font information from their parent by default. Using querySelectorAll, you can use the input[type=number] selector, just like you did in your css.
const celciusInput = document.querySelector("#celcius > input");
const farenheightInput = document.querySelector("#farenheight > input");
const kelvinInput = document.querySelector("#kelvin > input");
//Creating the funtion to convert celcius
function celciusConverter() {
const cTemp = parseFloat(celciusInput.value);
//Working out celcius to farenheight
const fTemp = (cTemp * (9/5) + 32);
//Working out celcius to kelvin
const kTemp = (cTemp + 273.15);
//Displaying the temperiture in all formats
farenheightInput.value = fTemp;
kelvinInput.value = kTemp;
document.querySelectorAll('input[type=number]').forEach(function (node) {
if (cTemp < 15) {
node.style.color = 'blue';
} else {
node.style.color = 'red';
}
})
}
//Refreshing the screen when a number is put in
celciusInput.addEventListener('input', celciusConverter);
#import url('https://fonts.googleapis.com/css?family=Oswald&display=swap');
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
body{
background: black;
}
div{
height: 33.333vh;
}
#Farenheight{
border-top: 5px;
border-bottom: 5px;
}
input[type=number]{
outline: none;
width: 100%;
height 100%;
background: black;
color: white;
font-size: 6em;
text-align: centre;
border: 0;
font-family: Oswald, sans-serif;
}
<body>
<div id="celcius" class"temperature">
<input type="number" placeholder="Celcius. . .">
</div>
<div id="farenheight" class"temperature">
<input type="number" placeholder="Farenheight. . .">
</div>
<div id="kelvin" class"temperature">
<input type="number" placeholder="Kelvin. . .">
</div>
</body>
The selector is incorrect. Don't put the # in front of the class name. getElementsByClassName just expects a string identical to the class name.
if (cTemp < 15){
document.getElementsByClassName('temperature')[0].style.color='black';
}
even better, I like to use querySelectorAll instead, which expects css like selectors.
I also assume you want to update the style of all of the .temperature elements. You can iterate over all of them instead of only updating the first one.
document.querySelectorAll('.temperature').forEach(function (node) {
if (cTemp < 15) {
node.style.color = 'blue';
} else {
node.style.color = 'red';
}
})

How to display 4 digits in the password field

I'm using normal JS and JSP which contains normal HTML tags. I have an input field with the type as PASSWORD which contains the maxlength of 10 digits.
Now I want to display the last 4 digits of the field values and other digits should be masked.
I'm not using jQuery and I want to use in normal JS.
So can anyone please suggest me any approach on it to achieve.
Try following these steps.
Get the password value.
Get the 2 parts (last 4 characters and the remaining leading characters).
Replace the leading characters with • (ASCII-7 character).
Generate new password to show (masked + 4 visible characters).
Set the password value.
Check out this fiddle.
Here is the snippet.
var passField = document.getElementById('pass');
passField.type = "text";
var passValue = passField.value;
var passLength = passValue.length;
var masked = passValue.substring(0, passLength - 4);
masked = masked.replace(/./g, '•'); //The character is ASCII-7 (Press Alt+7 to type)
var text = passValue.substring(passLength - 4);
var newPass = masked + text;
passField.value = newPass;
<input type='password' id='pass' value="ThisIsPassword" />
CSS
#wrapper {
position: relative;
}
#wrapper > input {
font-family: monospace;
text-align: right;
}
#wrapper > [type=password]::-ms-reveal{
display: none;
}
#passwordMasked {
width: 10em;
border: solid 1px black;
border-right: none;
}
#wrapper > #passwordUnmasked {
border: solid 1px black;
border-left: none;
width: 3em;
text-align: left;
}
#password {
position: absolute;
left: 0;
opacity: 0;
width: 13em;
}
HTML
<div id="wrapper">
<input type="password" onkeyup="updateunmasked()" id="passwordMasked" /><input type="text" id="passwordUnmasked" readonly /><input type="password" onkeyup="updateunmasked()" id="password" />
</div>
Javascript
function updateunmasked() {
var p = document.getElementById("password").value;
document.getElementById("passwordUnmasked").value = (' ' + p.substring(Math.max(p.length - 4, 0))).substring(Math.min(p.length, 4));
document.getElementById("passwordMasked").value = p.substring(4);
}
JSBin - https://jsbin.com/wijifupuco/1/edit?html,css,js,output

Javascript Loan Calculator with While loop

The program is supposed to determine how many months it will take to pay off the loan. Cannot seem to figure out how to fix my mathematical calculations. Not sure if it's the while loop that's wrong. Instead of determining the monthly payment based on user input, the input shows the total number of months (which i do not want. the program is supposed to do that). It is supposed to look like this: http://snag.gy/9vzGi.jpg Here is the code:
<html>
<head>
<title></title>
<script type="text/javascript">
function fixVal(value,numberOfCharacters,numberOfDecimals,padCharacter) {
var i, stringObject, stringLength, numberToPad;
value = value * Math.pow(10,numberOfDecimals);
value = Math.round(value);
stringObject = new String(value);
stringLength = stringObject.length;
while(stringLength < numberOfDecimals) {
stringObject = "0"+stringObject;
stringLength=stringLength+1;
}
if(numberOfDecimals>0) {
stringObject=stringObject.substring(0,stringLength-numberOfDecimals)+"."+
stringObject.substring(stringLength-numberOfDecimals,stringLength);
}
if (stringObject.length<numberOfCharacters && numberOfCharacters>0) {
numberToPad=numberOfCharacters-stringObject.length;
for (i=0; i<numberToPad; i=i+1) {
stringObject=padCharacter+stringObject;
}
}
return stringObject;
}
function buildTable() {
var amount=parseFloat(document.getElementById("loanAmt").value );
var numpay=parseInt(document.getElementById("monthlyPay").value );
var rate=parseFloat(document.getElementById("intRte").value );
rate = rate / 100;
var monthly = rate / 12;
var payment = ((amount * monthly) / (1-Math.pow((1 + monthly), - numpay)));
var total = payment * numpay;
var interest = total - amount;
var msg = "<table border='4' width='75%'>";
msg += "<tr>";
msg += "<td>Month</td>";
msg += "<td>Principal Paid</td>";
msg += "<td>Interest Paid</td>";
msg += "<td>Loan Balance</td>";
msg += "</tr>";
newPrincipal=amount;
var i = 1;
while (i <= numpay) {
newInterest=monthly*newPrincipal;
reduction=payment-newInterest;
newPrincipal=newPrincipal-reduction;
msg += "<tr><td align='left' bgcolor='pink'>"+i+"</td> \
<td align='left' bgcolor='pink'>"+fixVal(reduction,0,2,' ')+"</td> \
<td align='left' bgcolor='pink'>"+fixVal(newInterest,0,2,' ')+"</td> \
<td align='left' bgcolor='pink'>"+fixVal(newPrincipal,0,2,' ')+"</td></tr>";
i++;
}
msg += "</table>";
document.getElementById("results").innerHTML = msg;
}
</script>
<style type="text/css">
body {
background: black;
font-family: arial;
}
#contentwrap {
width: 700px;
margin: 40px auto 0px auto;
background: #FFFFCC;
text-align: center;
border: 6px red solid;
border-radius: 10px;
padding: 40px;
}
table {
border: 5px blue double;
background-color: #FFFFCC;
}
#header {
text-align: center;
font-size: 2.5em;
text-shadow: yellow 3px 3px;
margin-bottom: 18px;
color: red;
}
#button {
background: blue;
color: white;
cursor: pointer;
padding: 5px 0px 5px 0px;
border: 1px solid red;
border-radius: 25px;
width: 150px;
}
.contentTitles {
color: green;
font-weight: bold;
}
.style {
background: lightblue;
font-family: comic sans ms;
border: 6px blue double;
color: green;
font-weight: bold;
}
</style>
</head>
<body>
<div id="contentwrap">
<div id="header">Javascript Loan Calculator</div>
<form>
<div class="contentTitles">Enter Loan Amount<br />
<input type="text" id="loanAmt" class="style"><p />
Interest Rate (%)<br />
<input type="text" id="intRte" class="style"><p />
Monthly Payment Amount<br />
<input type="text" id="monthlyPay" class="style"><p />
<div style="margin-top:20px;">
<input type="button" value="Process Data" id="button" onClick="buildTable()">
</div>
</form>
<center>
<div id="results" style="margin-top:20px;"></div>
</center>
</div> <!-- ends div#contentwrap -->
</body>
</html>
If you want the input to be the monthly payment, please don't call the respective variable numpay.
In your case, it seems more practical not to calculate the number of months beforehand. You can use the while loop to build the table and calculate the duration of the loan at the same time:
function buildTable() {
var amount = parseFloat(document.getElementById("loanAmt").value );
var monthly = parseInt(document.getElementById("monthlyPay").value );
var rate = parseFloat(document.getElementById("intRte").value );
rate = rate / 100 / 12;
var m = 0; // number of months
while (amount > 0) {
var interest = amount * rate;
var principal = monthly - interest;
if (principal > amount) {
principal = amount;
amount = 0.0;
} else {
amount -= principal;
}
// build table: m + 1, principal, interest, amount
m++;
}
// display table
}

Categories

Resources