This is a portion of my code. Math and everything is working correctly. My issue is when the 'to submit' button is clicked. It runs through this code, all of the variables and inputs are saved correctly. My issue is that my outputs, 'Payment" and "pi" display on the website for a frame before the page are reloaded. Is there a way to make the output stay as well as the inputs the user puts into the fields?
<div id="div7" class="square">
<h1 padding-top="20px">Loan Information</h1>
<form>
<div class="col-25">Years</div><div class="col-75"><input type="number" id="years" min="0"></div><br>
<div class="col-25">Interest</div><div class="col-75"><input type="number" id="rate" min="0"></div><br>
<div class="col-25">Loan Amount</div><div class="col-75"><input type="number" id="amount" min="0"></div><br>
<button onclick="myFunction()">Calculate</button>
<input type="reset" value="Reset">
<h1 padding-top="25px">Loan Details</h1><br>
<div class="col-25">Monthly Payment</div><div class="col-75">:<output id="payment"></output></div><br>
<div class="col-25">P/I</div><div class="col-75">:<output id="pi"</output></div><br>
</form>
</div>
<script>
function myFunction(){
amt=eval(document.getElementById("amount").value);
yrs=eval(document.getElementById("years").value)*12;
rte=eval(document.getElementById("rate").value)/1200;
pmt=(rte+(rte/(Math.pow((1+rte),(yrs))-1)))*amt;
pmt=pmt*100;
mpt=Math.round(pmt);
pmt = pmt/100;
pi = (pmt*yrs)*100;
pi = Math.round(pi);
pi=pi/100;
document.getElementById("payment").innerHTML = payment ;
document.getElementById("pi").innerHTML = pi;
}
</script>
change your:
<button onclick="myFunction()">Calculate</button>
to:
<button onclick="return myFunction()">Calculate</button>
also, note that you are not defining any variables, it will make your code unmaintainable in the future, everything that you are creating is global.
here you have a working example, please note that I had to define the payment value because it was not defined.
function myFunction(e) {
//payment was not define so I'll just leave a 100 :)
payment = 100;
amt = eval(document.getElementById("amount").value);
yrs = eval(document.getElementById("years").value) * 12;
rte = eval(document.getElementById("rate").value) / 1200;
pmt = (rte + (rte / (Math.pow((1 + rte), (yrs)) - 1))) * amt;
pmt = pmt * 100;
mpt = Math.round(pmt);
pmt = pmt / 100;
pi = (pmt * yrs) * 100;
pi = Math.round(pi);
pi = pi / 100;
console.log(payment)
document.getElementById("payment").innerHTML = payment;
document.getElementById("pi").innerHTML = pi;
return false;
}
<div id="div7" class="square">
<h1 padding-top="20px">Loan Information</h1>
<form>
<div class="col-25">Years</div>
<div class="col-75"><input type="number" id="years" min="0"></div><br>
<div class="col-25">Interest</div>
<div class="col-75"><input type="number" id="rate" min="0"></div><br>
<div class="col-25">Loan Amount</div>
<div class="col-75"><input type="number" id="amount" min="0"></div><br>
<button onclick="return myFunction()">Calculate</button>
<input type="reset" value="Reset">
<h1 padding-top="25px">Loan Details</h1><br>
<div class="col-25">Monthly Payment</div>
<div class="col-75">:<output id="payment"></output></div><br>
<div class="col-25">P/I</div>
<div class="col-75">:<output id="pi" </output></div><br>
</form>
</div>
Related
I just started learning javascript few months ago. Recently i've been struggling to make this code work, but i end up messing up everything.
i want to make the reset button to clear user inputs?
Ive done several modification, but i couldn't still make it work. i dont know where i got it wrong.
Please i'll appreciate if anyone can assist me with this.
<div class=" DTRloading__form" style="display: block;">
<div class="form-container">
<div class="info">
</div>
<form class="form-inline">
<div class="form-group w-5 ">
<label for="red">Red Phase:</label>
<input type="number" class="form-control formInline" id="red" style="width: 80px">
</div>
<div class="form-group">
<label for="yellow">Yellow Phase:</label>
<input type="number" class="form-control formInline" id="yellow" style="width: 80px">
</div>
<div class="form-group">
<label for="blue">Blue Phase:</label>
<input type="number" class="form-control formInline" id="blue" style="width: 80px">
</div>
<div class="form-group">
<label for="neutral">Neutral:</label>
<input type="number" class="form-control formInline" id="neutral" style="width: 80px">
</div>
</form>
<label for="inputKVA" class="sr-only">DTR CAPACITY(Amp)</label>
<input type="number" id="inputKVA" class="form-control load" placeholder="DTR CAPACITY (KVA) *" required>
<button id="btnStart3" style="margin-top: 8px" class="btn btn2 btn-lg btn-primary btn-block ">Calculate</button>
</div>
<div class="output">
<h5 class="b-display">DTR Full Load Current is:</h5>
<div id="flA" class="form-control bill"></div>
<h5 class="b-display">The percentage Loading of this DTR is:</h5>
<div id="outputLoading" class="form-control bill"></div>
<!-- <div id="outputSum" class="form-control bill"></div>-->
<button id="btnRefresh3" class="btn btn2 btn-lg btn-primary btn-block">Reset</button>
</div>
</div>
<script>
document.getElementById("btnStart3").addEventListener('click', doCalc);
function doCalc() {
// Assign user inputs to variables
let x = parseFloat(document.querySelector("#red").value);
let y = parseFloat(document.querySelector("#yellow").value);
let z = parseFloat(document.querySelector("#blue").value);
let n = parseFloat(document.querySelector("#neutral").value);
const capacity = document.querySelector("#inputKVA");
const output2 = document.querySelector("#outputLoading");
const output3 = document.querySelector("#flA");
const start3 = document.getElementById("btnStart3");
const refresh3 = document.getElementById("btnRefresh3");
// // Call the average function
getAverage(x,y,z,n);
}
function getAverage(x,y,z,n) {
// Calculate the average
let average = ((((x + y + z + n) / 3) / (capacity.value * 1.391) )* 100);
// Display result to user
console.log(average);
outputLoading.innerHTML = average.toFixed(0) + "%";
//
}
const capacity = document.querySelector("#inputKVA");
function calculate(e) {
console.log(e);
e.preventDefault();
console.log("btnStart3 clicked");
var totalfLA = ((capacity.value * 1000) / (1.7321 * 415));
console.log(totalfLA);
flA.innerHTML = totalfLA.toFixed(1) + "A";
}
function emptyInput() {
console.log("emptied!");
outputKVA.innerHTML = "";
flA.innerHTML = "";
x.value = "";
y.value = "";
z.value = "";
n.value = "";
capacity.value = "";
output2.value = "";
output3.value = "";
}
btnStart3.addEventListener("click", calculate);
refresh3.addEventListener("click", emptyInput);
</script>
You can try in html with below button type as well.
<input type="reset" value="Reset">
If you want reset form from javascript then
document.getElementById("your-form-id").reset();
Change
1. <form class="form-inline">
2. refresh3.addEventListener("click", emptyInput);
to
1. <form class="form-inline" id="form">
2. document.getElementById("btnRefresh3").addEventListener("click", emptyInput);
3. function emptyInput() {
document.getElementById("form").reset();
}
I'm stuck on a problem. I'm working on an exercise that generates a random integer between 1-10. The user will submit a number from 1-10 in the input box. If a match occurs, the user will get an alert notifying them of success.
I'm stuck on getting the number from the user input. I want to log to the console the form input, but for the life of me, I cannot figure this out. I've tried changing the form type="number", type="text" and tried using parseInt().
Anything glaring in my code?
function exerciseEight() {
let input = document.querySelector("#number").value;
let button = document.querySelector("#guess");
let valueInt = parseInt(input, 10);
let number = Math.ceil(Math.random() * 10);
console.log(number);
button.onclick = function() {
console.log(input);
};
}
exerciseEight();
<body>
<div class="container container-fluid">
<p><strong>Exercise Eight:</strong> Guess a Number between 1 and 10.</p>
<form>
<div class="form-group">
<label for="number">Choose Number:</label>
<input id="number" value="" type="text" name="number" />
</form>
<!-- Result will go here -->
<p id="result"></p>
</div>
<button class="btn btn-dark" id="guess" type="submit">SUBMIT</button>
</body>
You need to get the input value when the user clicks. You're setting input and all the other variables that depend on it when the page is first loaded.
function exerciseEight() {
let button = document.querySelector("#guess");
let number = Math.ceil(Math.random() * 10);
button.onclick = function() {
let input = document.querySelector("#number").value;
let valueInt = parseInt(input, 10);
console.log(number, input);
};
}
exerciseEight();
<body>
<div class="container container-fluid">
<p><strong>Exercise Eight:</strong> Guess a Number between 1 and 10.</p>
<form>
<div class="form-group">
<label for="number">Choose Number:</label>
<input id="number" value="" type="text" name="number" />
</form>
<!-- Result will go here -->
<p id="result"></p>
</div>
<button class="btn btn-dark" id="guess" type="submit">SUBMIT</button>
</body>
The problem is that you are calling the function when the page loads, so it gets the values from the start, and doesn't change them at runtime when user enters input. You should call the function when user clicks the button.
function exerciseEight() {
let input = document.querySelector("#number").value;
let valueInt = parseInt(input, 10);
let number = Math.ceil(Math.random() * 10);
console.log(number);
}
let button = document.querySelector("#guess");
button.onclick = exerciseEight;
<body>
<div class="container container-fluid">
<p><strong>Exercise Eight:</strong> Guess a Number between 1 and 10.</p>
<form>
<div class="form-group">
<label for="number">Choose Number:</label>
<input id="number" value="" type="text" name="number" />
</form>
<!-- Result will go here -->
<p id="result"></p>
</div>
<button class="btn btn-dark" id="guess" type="submit">SUBMIT</button>
</body>
I have 2 html pages which are for a laundry services website and I have a javascript file. The first html page is called booking page where user get to book the number of clothes to be washed and it automatically calculate the total amount to be paid. Now on the second html page which is the summary page, I want the same amount on the booking page to reflect on the summary page showing the total amount and also also the buttons (plus and minus button) adding to it in the summary page.
I tried using localStorage for this project and I couldn't figure it out.
Skirt(s)</p>
<div>
<p>
<button type="button" class="sub" data-
target="skirts">−</button>
<input type="text" value="0"
class="field_skirts" />
<button type="button" class="add" data-
target="skirts">+</button>
<p class="display_skirts" name="price"
max="3" min="1">₦ 0</p>
</p>
</div>
</div>
<div>
<div class="second-booking-container-image"><img
src="./img/blouse.png" /></div>
<p class="second-booking-container-icon"
name="product" value="100" id="qnty_4">
Blouse(s)</p>
<div>
<p>
<button type="button" class="sub" data-
target="blouses">-</button>
<input type="text" value="0"
class="field_blouses" />
<button type="button" class="add" data-
target="blouses">+</button>
<p class="display_blouses" name="price"
max="3" min="1">₦ 0</p>
</p>
</div>
</div>
<div>
<div class="second-booking-container-image"><img
src="./img/jacket.png" /></div>
<p class="second-booking-container-icon-long"
name="product" value="100" id="qnty_5">Suit/Jacket(s)
</p>
<p>
<button type="button" class="sub" data-
target="suits">-</button>
<input type="text" value="0" class="field_suits"
/>
<button type="button" class="add" data-
target="suits">+</button>
<p class="display_suits" name="price" max="3"
min="1">₦ 0</p>
</p>
</div>
</div>
<div class="third-booking-container">
<p>Total:₦ <span id="totalValue"></span></p>
<button>Set pick up date
<FontAwesomeIcon class="second-container-button-right"
icon="angle-right" /></button>
</div>
</div>
var subElm = document.querySelectorAll('.sub');
var addElm = document.querySelectorAll('.add');
var totalValueElm = document.getElementById('totalValue');
for (var i = 0; i < subElm.length; i++) {
subElm[i].addEventListener('click', function () {
var targetItem = this.getAttribute('data-target');
var inputElm = document.querySelector('.field_' + targetItem);
var displayElm = document.querySelector('.display_' +
targetItem);
var currentValue = +inputElm.getAttribute('value');
if (currentValue !== 0) {
var incValue = currentValue - 1;
var strValue = ' ' + incValue;
inputElm.setAttribute('value', incValue);
// displayElm.innerHTML = "₦" + strValue;
displayElm.innerHTML = "₦ " + incValue * 100;
totalValueElm.innerText = Number(totalValueElm.innerText) -
100;
}
});
addElm[i].addEventListener('click', function () {
var targetItem = this.getAttribute('data-target');
var inputElm = document.querySelector('.field_' + targetItem);
var displayElm = document.querySelector('.display_' +
targetItem);
var currentValue = +inputElm.getAttribute('value');
var incValue = currentValue + 1;
var strValue = ' ' + incValue;
inputElm.setAttribute('value', incValue);
// displayElm.innerHTML = "₦" + strValue;
displayElm.innerHTML = "₦ " + incValue * 100;
totalValueElm.innerText = Number(totalValueElm.innerText) + 100;
});
}
<div class="summaryContainer">
<div class="summaryNavBar"><p
className="summaryTitle">Summary</p></div>
<div class="summaryContent">
<p class="total" id="total">Total:</p>
<p class="sum">₦0.00</p>
</div>
<div class="summaryCard">
<div class="summary-card-title">
<div>Item</div>
<div>Quantity</div>
</div>
<div class="summary-card-content">
<div >Shirt(s)</div><div id="
first" class="summary-quantity"><button type="button"
id="sub" class="sub">−</button>
<input type="text" id="1" value="0" class="field" />
<button type="button" id="add" class="add">+</button>
</div>
</div>
<div class="summary-card-content">
<div>Trouser(s)</div>
<div class="summary-quantity" id="second">
<button type="button" id="sub" class="sub">−</button>
<input type="text" id="1" value="0" class="field" />
<button type="button" id="add" class="add">+</button>
</div>
</div>
<div class="summary-card-content" id="third">
I want the total calculation of price on the booking page to also appear at the summary page when I automatically click on summary page
In your booking page, store the total price in local storage using localStorage.setItem().
localStorage.setItem('totalPrice', JSON.stringify(totalValue));
In your summary page, access this total price using localStorage.getItem().
var totalPrice = JSON.parse(localStorage.getItem('totalPrice'));
Note that all the values are stored as strings, so you have to use JSON.parse() to convert the string back to the object or value.
I've done this JavaScript calculation. Live Preview
Everything is okay but the problem is, Once the calculation is done, the next time it shows NAN value. If you do not reload the page, then you can not calculation!
I want to repeat the calculation without reloading, how could it be?
Here Is my Simple Calculation:
// get all data
var first = document.getElementById('first');
var second = document.getElementById('second');
var third = document.getElementById('third');
var four = document.getElementById('four');
var five = document.getElementById('five');
var six = document.getElementById('six');
var seven = document.getElementById('seven');
var eight = document.getElementById('eight');
var outPut = document.getElementById('result');
// Listen for Submit the form
document.getElementById('gpaInput').addEventListener('submit', outPutF);
function outPutF(e){
e.preventDefault();
// Calculation
first = first.value * 5 / 100;
second = second.value * 5 / 100;
third = third.value * 5 / 100;
four = four.value * 15 / 100;
five = five.value * 15 / 100;
six = six.value * 20 / 100;
seven = seven.value * 25 / 100;
eight = eight.value * 10 / 100;
var result = first + second + third + four + five + six + seven + eight;
// Reset the form
this.reset();
// Finally output the Calculation
outPut.innerHTML = 'Your CGPA: '+result;
// setTimeout(window.location.reload(true), 9000);
}
input:focus, button:focus, select:focus {outline: none!important;box-shadow: none!important;}
#gpaInput .input-group {margin: 0.5em 0;}
#gpaInput .input-group-text { min-width: 95px;}
#result {display: block; width: 68%; text-align: center; margin-top: 25px; padding: 17px 0;}
.jumbotron {overflow: hidden;}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
<div class="row justify-content-center">
<div class="col-lg-6">
<form id="gpaInput">
<div class="input-group">
<input id="first" type="number" step="any" class="form-control">
</div>
<div class="input-group">
<input id="second" type="number" step="any" class="form-control">
</div>
<div class="input-group">
<input id="third" type="number" step="any" class="form-control">
</div>
<div class="input-group">
<input id="four" type="number" step="any" class="form-control">
</div>
<div class="input-group">
<input id="five" type="number" step="any" class="form-control">
</div>
<div class="input-group">
<input id="six" type="number" step="any" class="form-control">
</div>
<div class="input-group">
<input id="seven" type="number" step="any" class="form-control">
</div>
<div class="input-group">
<input id="eight" type="number" step="any" class="form-control">
</div>
<hr>
<div class="mt-4">
<button type="submit" class="btn btn-info float-left p-3">Calculate CGPA</button>
<h5 id="result" class="alert alert-success float-right mt-0">Complete The form!</h5>
</div>
</form>
</div>
</div>
</div>
You get NaN because you are replacing the reference to the element with its value , so on the second time it is not longer the element.
var first = document.getElementById('first'); //<-- element
first = first.value * 5 / 100; //<-- first replaced with a number
so than next time you call it
first = first.value * 5 / 100; //<-- first.value is undefined here since first is a number
So you need to rename your variables inside...
var nFirst = first.value * 5 / 100;
var nSecond = second.value * 5 / 100;
var nThird = third.value * 5 / 100;
var nFour = four.value * 15 / 100;
var nFive = five.value * 15 / 100;
var nSix = six.value * 20 / 100;
var nSeven = seven.value * 25 / 100;
var nEight = eight.value * 10 / 100;
var result = nFirst + nSecond + nThird + nFour + nFive + nSix + nSeven + nEight;
You Should Declare your variables inside your function or you can get the value of every fields inside the function so that when the code runs for the next time it will get the values again correctly,
// Listen for Submit the form
document.getElementById('gpaInput').addEventListener('submit', outPutF);
function outPutF(e){
var first = document.getElementById('first');
var second = document.getElementById('second');
var third = document.getElementById('third');
var four = document.getElementById('four');
var five = document.getElementById('five');
var six = document.getElementById('six');
var seven = document.getElementById('seven');
var eight = document.getElementById('eight');
var outPut = document.getElementById('result');
e.preventDefault();
// Calculation
first = first.value * 5 / 100;
second = second.value * 5 / 100;
third = third.value * 5 / 100;
four = four.value * 15 / 100;
five = five.value * 15 / 100;
six = six.value * 20 / 100;
seven = seven.value * 25 / 100;
eight = eight.value * 10 / 100;
var result = first + second + third + four + five + six + seven + eight;
// Reset the form
this.reset();
// Finally output the Calculation
outPut.innerHTML = 'Your CGPA: '+result;
// setTimeout(window.location.reload(true), 9000);
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
<div class="row justify-content-center">
<div class="col-lg-6">
<form id="gpaInput">
<div class="input-group">
<input id="first" type="number" step="any" class="form-control">
</div>
<div class="input-group">
<input id="second" type="number" step="any" class="form-control">
</div>
<div class="input-group">
<input id="third" type="number" step="any" class="form-control">
</div>
<div class="input-group">
<input id="four" type="number" step="any" class="form-control">
</div>
<div class="input-group">
<input id="five" type="number" step="any" class="form-control">
</div>
<div class="input-group">
<input id="six" type="number" step="any" class="form-control">
</div>
<div class="input-group">
<input id="seven" type="number" step="any" class="form-control">
</div>
<div class="input-group">
<input id="eight" type="number" step="any" class="form-control">
</div>
<hr>
<div class="mt-4">
<button type="submit" class="btn btn-info float-left p-3">Calculate CGPA</button>
<h5 id="result" class="alert alert-success float-right mt-0">Complete The form!</h5>
</div>
</form>
</div>
</div>
</div>
Been stuck on this for a few hours, running out of ideas. I have two BMI equations (metric, standard), both working correctly. I have them set up in Jquery UI tabs with a form. The first equation (metric) works perfectly. I can't seem to get the second equation to work. It works when it's standalone, but not when I insert it with the first equation. Should I have not created a new script tag for the second equation?
<html>
<head>
<link rel="stylesheet" href="../jquery-ui/jquery-ui.min.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="../jquery-mousewheel-master/jquery.mousewheel.min.js"></script>
<script>
$(function() {
// get user input
var input = function() {
var height = $("#height").val();
var weight = $("#weight").val();
var calculated_bmi = BMI(height, weight);
$('#result').text(calculated_bmi);
}
var BMI = function(h, w) {
// convert into centimeters
var h = h / 100;
var h_squared = h * h;
var result = w / h_squared;
return result.toFixed(1);
}
$("#calculate").click(function() {
input();
})
$(function() {
$("#tabs").tabs();
});
$("#weight").spinner();
$("#height").spinner();
});
</script>
<script>
"use strict";
$(function() {
$("#bmicalc").submit(function(e) {
e.preventDefault();
var heightFt = $("#height_ft").val();
heightIn = $("#height_in").val();
height = parseFloat(heightFt * 12) + parseFloat(heightIn);
weight = $("#weight1").val();
BMI = calculateBMI(height, weight);
$("#result2").text('Your BMI is ' + BMI);
});
function calculateBMI(height, weight) {
var BMI = (weight / (height * height)) * 703
return Math.round(BMI * Math.pow(10, 2)) / Math.pow(10, 2);
}
$("#weight").spinner();
$("#height").spinner();
$("#height_ft").spinner();
$("#height_in").spinner();
$("#weight1").spinner();
});
</script>
</head>
<body>
<div class="wrapper">
<h2 class="subtitle">Enter your information</h2>
<form id="bmicalc">
<div id="tabs">
<ul>
<li>Metric</li>
<li>Standard</li>
</ul>
<div id="tabs-1">
<div>
<div>
Height (centimeters): <input type="spinner" id="height" min="1" max="300"> Weight (kilograms): <input type="spinner" id="weight" min="1" max="450">
</div>
<input type="button" id="calculate" value="Calculate">
<p class="resultwords">Your BMI is: <span id="result"></span></p>
</div>
</div>
<div id="tabs-2">
<div id="calc-id2">
<p>
<label>Height:
<input type="text" id="height_ft" min="1" max="10">feet
<input type="text" id="height_in" min="1" max="11">inches</label>
</p>
<p>
<label>Weight:
<input type="text" id="weight1" min="1" max="1000">pounds</label>
</p>
<input type="submit" id="bmicalc1" value="Calculate">
<p class="resultwords">Your BMI is: <span id="result2"></span></p>
</div>
</div>
</div>
</form>
</div>
</body>
</html>