Javascript Function Returning NaN - javascript

I'm making a calculator that will take inputs from a survey form and then push results to an object so I can display it on other parts of the site and use chart.js
However, I can't get the first calculation to work. My first function is to calculate the 30% saving of monthly gas spend (gas) and to subtract the saving from a monthly payment (price). I'm getting NaN in the console when the site loads even before clicking the button which has the eventlistener assigned to it.
Where am I going wrong?
P.S I haven't made the form responsive yet so it will need to be viewed in a full browser.
const calculate = document.getElementById('one');
calculate.addEventListener('click', calc());
function calc() {
let gas = parseInt(document.getElementById('gas').value);
let price = parseInt(document.getElementById('price').value);
let gasSaving;
let result;
gasSaving = gas * 0.3;
result = price - gasSaving;
console.log(result);
}
/* Survery Section Start */
.survery {
background-color: #1b262c;
padding-bottom: 100px;
}
.survery-h1 {
color: white;
text-align: center;
padding-top: 5rem;
}
input {
text-indent: 10px;
}
.survery-questions {
display: flex;
flex-direction: row;
flex-wrap: wrap;
}
.home-name-footer {
width: 600px;
height: 45px;
margin-bottom: 3em;
margin-left: 90px;
margin-right: 25px;
}
.home-phone-footer {
height: 45px;
margin-bottom: 3em;
width: 600px;
margin-left: 25px;
}
.home-email-footer {
width: 600px;
height: 45px;
margin-bottom: 3em;
margin-left: 90px;
margin-right: 25px;
}
#input {
background: #ffffff;
border: 1px solid #eaeaea;
}
.btn-calc {
padding: 1rem 2.5rem;
width: 15rem;
background-color: #168ecf;
text-transform: uppercase;
text-decoration: none;
font-family: 'Roboto', sans-serif;
font-size: 1rem;
font-weight: 900;
color: #eee;
transition: all .5s;
margin-bottom: 3rem;
margin-top: 1rem;
text-align: center;
}
<html>
<head>
</head>
<body>
<!-- Survery Start -->
<section class="survery">
<div class="survery-title">
<h1 class="survery-h1">Scrappage Payment Survey</h1>
</div>
<form action="">
<div class="survery-questions">
<div class="name-form">
<input type="text" placeholder="Gas Supplier" class="home-name-footer" id="input" required>
</div>
<div class="phone-form">
<input type="text" placeholder="Gas Meter Serial No." class="home-phone-footer" id="input" required>
</div>
<div class="email-form">
<input placeholder="Monthly Gas Spend" class="home-email-footer" id="gas" required>
</div>
<div class="phone-form">
<input type="text" placeholder="System Monthly Payment" class="home-phone-footer" id="price" required>
</div>
<div class="name-form">
<input type="text" placeholder="Number Of Bathrooms" class="home-name-footer" id="input" required>
</div>
<div class="phone-form">
<input type="text" placeholder="Number Of Radiators" class="home-phone-footer" id="input" required>
</div>
<div class="name-form">
<input type="text" placeholder="System Size Required (Kw)" class="home-name-footer" id="input" required>
</div>
<div class="phone-form">
<input type="text" placeholder="Number Of Residents" class="home-phone-footer" id="input" required>
</div>
<div class="thebutton">
<button class="btn-calc" id="one">Calculate</button>
</form>
</div>
</div>
</section>
<!-- Survery End-->
</body>
</html>

calculate.addEventListener('click', calc());
to
calculate.addEventListener('click', calc);
the calc() with parentheses will execute the function directly, whilst without it will only be called upon.
Also, you should add an event prevent default to not having the page refreshed.
const calculate = document.getElementById('one');
calculate.addEventListener('click', calc);
function calc(event) {
// Prevent page refresh.
event.preventDefault();
let gas = parseInt(document.getElementById('gas').value);
let price = parseInt(document.getElementById('price').value);
let gasSaving;
let result;
gasSaving = gas * 0.3;
result = price - gasSaving;
console.log(result);
}

I have tried to solve the issue: Please check
const calculate = document.getElementById('one');
calculate.addEventListener('click', calc);
function calc() {
let gas = parseInt(document.getElementById('gas').value);
let price = parseInt(document.getElementById('price').value);
let gasSaving;
let result;
gasSaving = gas * 0.3;
result = price - gasSaving;
console.log(result);
}
/* Survery Section Start */
.survery {
background-color: #1b262c;
padding-bottom: 100px;
}
.survery-h1 {
color: white;
text-align: center;
padding-top: 5rem;
}
input {
text-indent: 10px;
}
.survery-questions {
display: flex;
flex-direction: row;
flex-wrap: wrap;
}
.home-name-footer {
width: 600px;
height: 45px;
margin-bottom: 3em;
margin-left: 90px;
margin-right: 25px;
}
.home-phone-footer {
height: 45px;
margin-bottom: 3em;
width: 600px;
margin-left: 25px;
}
.home-email-footer {
width: 600px;
height: 45px;
margin-bottom: 3em;
margin-left: 90px;
margin-right: 25px;
}
#input {
background: #ffffff;
border: 1px solid #eaeaea;
}
.btn-calc {
padding: 1rem 2.5rem;
width: 15rem;
background-color: #168ecf;
text-transform: uppercase;
text-decoration: none;
font-family: 'Roboto', sans-serif;
font-size: 1rem;
font-weight: 900;
color: #eee;
transition: all .5s;
margin-bottom: 3rem;
margin-top: 1rem;
text-align: center;
}
<html>
<head>
</head>
<body>
<!-- Survery Start -->
<section class="survery">
<div class="survery-title">
<h1 class="survery-h1">Scrappage Payment Survey</h1>
</div>
<form action="">
<div class="survery-questions">
<div class="name-form">
<input type="text" placeholder="Gas Supplier" class="home-name-footer" id="input" required>
</div>
<div class="phone-form">
<input type="text" placeholder="Gas Meter Serial No." class="home-phone-footer" id="input" required>
</div>
<div class="email-form">
<input placeholder="Monthly Gas Spend" class="home-email-footer" id="gas" required>
</div>
<div class="phone-form">
<input type="text" placeholder="System Monthly Payment" class="home-phone-footer" id="price" required>
</div>
<div class="name-form">
<input type="text" placeholder="Number Of Bathrooms" class="home-name-footer" id="input" required>
</div>
<div class="phone-form">
<input type="text" placeholder="Number Of Radiators" class="home-phone-footer" id="input" required>
</div>
<div class="name-form">
<input type="text" placeholder="System Size Required (Kw)" class="home-name-footer" id="input" required>
</div>
<div class="phone-form">
<input type="text" placeholder="Number Of Residents" class="home-phone-footer" id="input" required>
</div>
<div class="thebutton">
<button class="btn-calc" id="one">Calculate</button>
</form>
</div>
</div>
</section>
<!-- Survery End-->
</body>
</html>
Hope, it will help you

Step #1
I added jquery reference in the head
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
Step #2
I added onclick event to call calc() function
Calculate
Step #3
I added this script now it's working fine
function calc() {
debugger
let gas = parseInt(document.getElementById('gas').value);
let price = parseInt(document.getElementById('price').value);
let gasSaving;
let result;
gasSaving = gas * 0.3;
result = price - gasSaving;
console.log(result);
}
What I understand your are not properly calling the event that's why NAN(Not a Number) is appearing in the console and the second thing you asked in the comment about round off it is very simple
https://www.w3schools.com/JSREF/jsref_round.asp
please check this link it will help you

Related

Problem with script that is suppose to add two numbers

I wrote up a code designed to add two numbers and it keeps returning a NaN when I ask for an answer, I am fairly new but would like to know why this code in particular does not work so I can make sure I don't make the mistake again.
HTML
<html>
<head>
<link rel="stylesheet" href="styles.css">
<title>April23</title>
</head>
<body>
<!--Top Portion-->
<div class="container1">
<div class="calculator">
<label for="num1" id="num1">Enter First Number </label>
<input type="text" id="number0" name=num1 size=10>
</div>
<div class="calculator">
<label for="num2" id="num2">Enter Second Number</label>
<input type="text" id="number1" name=num1 size=10>
</div>
<div class="calculator2" id="button">
<button id="btn">Get Result</button>
</div>
<div class="calculator">
<label for="num2" id="sum"> Sum </label>
<input type="text" id="number" name=num1 size=10>
</div>
</div>
<div class="container1" id="c2"></div>
<div class="container1"></div>
</body>
<script src="main.js"></script>
</html>
JavaScript
/*this portion is to check if the blank input boxes are filled or not*/
const num1 = document.querySelector('#number0');
const num2 = document.querySelector('#number1');
/*this portion is to grab the value of the input boxes if they are filled*/
var number1=document.getElementById("number0").value;
var number2=document.getElementById("number1").value;
/*this portion is to convert the values into integers*/
x = parseInt(number1);
y = parseInt(number2);
const calc = document.querySelector(".calculator2");
calc.addEventListener('click', (e)=>
{
e.preventDefault();
if(num1.value==='' || num2.value ===''){
alert('please enter both numbers');
}
else{
alert(x+y);
}
}
)
So the first condition works and sends an alert box asking to input two numbers, the second condition returns a an Alert box with NaN instead of adding the two numbers
css
body{
margin: 0;;
/*background: url('image0.jpg') no-repeat; ;*/
font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
background-color: thistle;
}
.container1{
position: relative;
height: 50vh;
background: rgb(39, 105, 160);
opacity: 0.9;
display: flex;
flex-direction: column;
justify-content: center;
gap: 2rem;
}
.calculator{
margin-left: 4rem;
}
#number{
margin-left: 7.5rem;
}
#number0{
margin-left: 1rem;
}
#c2{
background-color: rgb(196, 169, 169);
}
.calculator2{
margin-left: 4rem;
}
Take out the number after you click on the button not before. Everything else is great.
TIP: As you are adding the number there must be always a type number so it would be better to add type="number" on input so that the user cannot enter alphabets or special characters.
const calc = document.querySelector(".calculator2");
calc.addEventListener("click", (e) => {
e.preventDefault();
const x = document.querySelector("#number0").value;
const y = document.querySelector("#number1").value;
if (x === "" || y === "") {
alert("please enter both numbers");
} else {
alert(parseInt(x) + parseInt(y));
}
});
body {
margin: 0;
;
/*background: url('image0.jpg') no-repeat; ;*/
font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
background-color: thistle;
}
.container1 {
padding: 2rem;
position: relative;
height: 50vh;
background: rgb(39, 105, 160);
opacity: 0.9;
display: flex;
flex-direction: column;
justify-content: center;
gap: 2rem;
}
.calculator {
margin-left: 4rem;
}
#number {
margin-left: 7.5rem;
}
#number0 {
margin-left: 1rem;
}
#c2 {
background-color: rgb(196, 169, 169);
}
.calculator2 {
margin-left: 4rem;
}
<div class="container1">
<div class="calculator">
<label for="num1" id="num1">Enter First Number </label>
<input type="number" id="number0" name=num1 size=10>
</div>
<div class="calculator">
<label for="num2" id="num2">Enter Second Number</label>
<input type="number" id="number1" name=num1 size=10>
</div>
<div class="calculator2" id="button">
<button id="btn">Get Result</button>
</div>
<div class="calculator">
<label for="num2" id="sum"> Sum </label>
<input type="text" id="number" name=num1 size=10>
</div>
</div>
<div class="container1" id="c2"></div>
<div class="container1"></div>

Creating a macro calculator - getting a NaN result when trying to add a drop down menu

The calculator was working fine until I added the activity level from the drop down. Depending on the users selection for activity level, the value returned should be multiplied by the corresponding value associated with each activity level. I have added the values that it should be multiplying the result by. However, it doesn't seem to be seeing the 'activityLevel' variable inside the function. Am I not declaring this properly? When I try to run the code, it returns a NaN result.
/* Calculate female macros */
(function() {
function calculateFemale(femaleWeight, femaleHeight, femaleAge) {
femaleWeight = parseFloat(femaleWeight);
femaleHeight = parseFloat(femaleHeight);
femaleAge = parseFloat(femaleAge);
activityLevel = (activityLevel);
return (((femaleWeight * 4.3) + (femaleHeight * 4.7) - (femaleAge * 4.7) * activityLevel);
}
var womanBMR = document.getElementById("womanBMR");
if (womanBMR) {
womanBMR.onsubmit = function() {
this.result.value = calculateFemale(this.femaleWeight.value, this.femaleHeight.value, this.femaleAge.value, this.activityLevel.value);
return false;
};
}
}());
/* Calculate male macros */
(function() {
function calculateMale(maleWeight, maleHeight, maleAge) {
maleWeight = parseFloat(maleWeight);
maleHeight = parseFloat(maleHeight);
maleAge = parseFloat(maleAge);
activityLevel = (activityLevel);
return (((maleWeight * 6.3) + (maleHeight * 12.9) - (maleAge * 6.8) + 66) * activityLevel);
}
var maleBMR = document.getElementById("manBMR");
if (manBMR) {
manBMR.onsubmit = function() {
this.result.value = calculateMale(this.maleWeight.value, this.maleHeight.value, this.maleAge.value, this.activityLevel.value);
return false;
};
}
}());
* {
box-sizing: border-box;
}
img {
max-width: 100%;
}
.w-button {
display: inline-block;
padding: 9px 15px;
background-color: #3898EC;
color: white;
border: 0;
border-radius: 0;
}
p {
margin-top: 0;
margin-bottom: 10px;
}
.w-container {
margin-left: auto;
margin-right: auto;
max-width: 940px;
}
.w-row:before,
.w-row:after {
content: " ";
display: table;
}
.w-row:after {
clear: both;
}
.w-col {
position: relative;
float: left;
width: 100%;
min-height: 1px;
padding-left: 10px;
padding-right: 10px;
}
.w-col .w-col {
padding-left: 0;
padding-right: 0;
}
.w-col-1 {
width: 8.33333333%;
}
.w-col-2 {
width: 91.66666667%;
}
body {
margin: 0;
background-color: #fff;
font-family: Arial, sans-serif;
font-size: 14px;
line-height: 20px;
color: #333;
}
h1 {
font-size: 38px;
line-height: 44px;
margin-top: 20px;
}
h2 {
margin-top: 20px;
margin-bottom: 10px;
color: #f70909;
font-size: 32px;
line-height: 36px;
font-weight: 400;
}
.text-block {
position: relative;
left: 100px;
}
.text-block-3 {
margin-top: 20px;
padding-left: 100px;
}
.text-block-4 {
padding-top: 20px;
padding-left: 20px;
}
.list {
padding-left: 140px;
}
.div-block {
font-style: italic;
font-weight: 400;
}
.paragraph {
padding-top: 20px;
}
.container {
margin-top: 0px;
}
.button {
margin-top: 20px;
margin-left: 100px;
background-color: #020202;
}
.column-1 {
background-color: #f0e8e8;
}
.image {
padding-left: 20px;
}
<!DOCTYPE html>
<head>
<title>Calculator</title>
<link href="css/style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="w-row">
<div class="w-col w-col-1"><img src="images/apple.jpg" alt="apple"></div>
<div class="column-1 w-col w-col-2">
<h1>Healthy Eating</h1>
</div>
</div>
<div class="w-container">
<h2>Calculator</h2>
</div>
<div class="w-container">
<div><em>Use the form below if you are female.</em></div>
<form id="womanBMR">
<fieldset>
<p>
<label for="femaleWeight">Weight (lbs)</label>
<input id="femaleWeight" name="femaleWeight" type="number" />
</p>
<p>
<label for="femaleHeight">Height (inches)</label>
<input id="femaleHeight" name="femaleHeight" type="number" />
</p>
<p>
<label for="femaleAge">Ages (years)</label>
<input id="femaleAge" name="femaleAge" type="number" />
</p>
<p>
<select id = "selActivity">
<option value = "1.2">Sedentary</option>
<option value = "1.375">Light Activity</option>
<option value = "1.55">Moderate Activity</option>
<option value = "1.725">Very Active</option>
<option value = "1.9">Extra Active</option>
</select>
</p>
<p>
<input type="submit" value="Calculate" />
</p>
<p>
<label for="result">Base Calories Per Day</label>
<input id="result" name="result" />
</p>
<p>
<input type="reset" value="Clear" />
</p>
</fieldset>
</form>
</div>
<div class="w-container">
<div><em>Use the form below if you are male.</em></div>
<form id="manBMR">
<fieldset>
<p>
<label for="maleWeight">Weight (lbs)</label>
<input id="maleWeight" name="maleWeight" type="number" />
</p>
<p>
<label for="maleHeight">Height (inches)</label>
<input id="maleHeight" name="maleHeight" type="number" />
</p>
<p>
<label for="maleAge">Ages (years)</label>
<input id="maleAge" name="maleAge" type="number" />
</p>
<p>
<select id = "activityLevel">
<option value = "1.2">Sedentary</option>
<option value = "1.375">Light Activity</option>
<option value = "1.55">Moderate Activity</option>
<option value = "1.725">Very Active</option>
<option value = "1.9">Extra Active</option>
</select>
</p>
<p>
<input type="submit" value="Calculate" />
</p>
<p>
<label for="result">Base Calories Per Day</label>
<input id="result" name="result" />
</p>
<p>
<input type="reset" value="Clear" />
</p>
</fieldset>
</form>
</div>
<script src="js/calculatorscript.js"></script>
HomeRecipesTipsFAQ
</body>
</html>
You forgot to add the parameter to the function definition and to call parseFloat
/* Calculate female macros */
(function() {
function calculateFemale(femaleWeight, femaleHeight, femaleAge) {
femaleWeight = parseFloat(femaleWeight);
femaleHeight = parseFloat(femaleHeight);
femaleAge = parseFloat(femaleAge);
return ((femaleWeight * 4.3) + (femaleHeight * 4.7) - (femaleAge * 4.7) + 655);
}
var womanBMR = document.getElementById("womanBMR");
if (womanBMR) {
womanBMR.onsubmit = function() {
this.result.value = calculateFemale(this.femaleWeight.value, this.femaleHeight.value, this.femaleAge.value);
return false;
};
}
}());
/* Calculate male macros */
//*This function calculates the macros for a male, it requires three variables be input
//*by the user. Their weight, height, and age. It then returns the
(function() {
function calculateMale(maleWeight, maleHeight, maleAge, activityLevel) {
maleWeight = parseFloat(maleWeight);
maleHeight = parseFloat(maleHeight);
maleAge = parseFloat(maleAge);
activityLevel = parseFloat(activityLevel);
return (((maleWeight * 6.3) + (maleHeight * 12.9) - (maleAge * 6.8) + 66) * activityLevel);
}
var maleBMR = document.getElementById("manBMR");
if (manBMR) {
manBMR.onsubmit = function() {
this.result.value = calculateMale(this.maleWeight.value, this.maleHeight.value, this.maleAge.value, this.activityLevel.value);
return false;
};
}
}());
* {
box-sizing: border-box;
}
img {
max-width: 100%;
}
.w-button {
display: inline-block;
padding: 9px 15px;
background-color: #3898EC;
color: white;
border: 0;
border-radius: 0;
}
p {
margin-top: 0;
margin-bottom: 10px;
}
.w-container {
margin-left: auto;
margin-right: auto;
max-width: 940px;
}
.w-row:before,
.w-row:after {
content: " ";
display: table;
}
.w-row:after {
clear: both;
}
.w-col {
position: relative;
float: left;
width: 100%;
min-height: 1px;
padding-left: 10px;
padding-right: 10px;
}
.w-col .w-col {
padding-left: 0;
padding-right: 0;
}
.w-col-1 {
width: 8.33333333%;
}
.w-col-2 {
width: 91.66666667%;
}
body {
margin: 0;
background-color: #fff;
font-family: Arial, sans-serif;
font-size: 14px;
line-height: 20px;
color: #333;
}
h1 {
font-size: 38px;
line-height: 44px;
margin-top: 20px;
}
h2 {
margin-top: 20px;
margin-bottom: 10px;
color: #f70909;
font-size: 32px;
line-height: 36px;
font-weight: 400;
}
.text-block {
position: relative;
left: 100px;
}
.text-block-3 {
margin-top: 20px;
padding-left: 100px;
}
.text-block-4 {
padding-top: 20px;
padding-left: 20px;
}
.list {
padding-left: 140px;
}
.div-block {
font-style: italic;
font-weight: 400;
}
.paragraph {
padding-top: 20px;
}
.container {
margin-top: 0px;
}
.button {
margin-top: 20px;
margin-left: 100px;
background-color: #020202;
}
.column-1 {
background-color: #f0e8e8;
}
.image {
padding-left: 20px;
}
<!DOCTYPE html>
<head>
<title>Calculator</title>
<link href="css/style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="w-row">
<div class="w-col w-col-1"><img src="images/apple.jpg" alt="apple"></div>
<div class="column-1 w-col w-col-2">
<h1>Healthy Eating</h1>
</div>
</div>
<div class="w-container">
<h2>Calculator</h2>
</div>
<div class="w-container">
<div><em>Use the form below if you are female.</em></div>
<form id="womanBMR">
<fieldset>
<p>
<label for="femaleWeight">Weight (lbs)</label>
<input id="femaleWeight" name="femaleWeight" type="number" />
</p>
<p>
<label for="femaleHeight">Height (inches)</label>
<input id="femaleHeight" name="femaleHeight" type="number" />
</p>
<p>
<label for="femaleAge">Ages (years)</label>
<input id="femaleAge" name="femaleAge" type="number" />
</p>
<p>
<select id = "selActivity">
<option value = "1.2">Sedentary</option>
<option value = "1.375">Light Activity</option>
<option value = "1.55">Moderate Activity</option>
<option value = "1.725">Very Active</option>
<option value = "1.9">Extra Active</option>
</select>
</p>
<p>
<input type="submit" value="Calculate" />
</p>
<p>
<label for="result">Base Calories Per Day</label>
<input id="result" name="result" />
</p>
<p>
<input type="reset" value="Clear" />
</p>
</fieldset>
</form>
</div>
<div class="w-container">
<div><em>Use the form below if you are male.</em></div>
<form id="manBMR">
<fieldset>
<p>
<label for="maleWeight">Weight (lbs)</label>
<input id="maleWeight" name="maleWeight" type="number" />
</p>
<p>
<label for="maleHeight">Height (inches)</label>
<input id="maleHeight" name="maleHeight" type="number" />
</p>
<p>
<label for="maleAge">Ages (years)</label>
<input id="maleAge" name="maleAge" type="number" />
</p>
<p>
<select id = "activityLevel">
<option value = "1.2">Sedentary</option>
<option value = "1.375">Light Activity</option>
<option value = "1.55">Moderate Activity</option>
<option value = "1.725">Very Active</option>
<option value = "1.9">Extra Active</option>
</select>
</p>
<p>
<input type="submit" value="Calculate" />
</p>
<p>
<label for="result">Base Calories Per Day</label>
<input id="result" name="result" />
</p>
<p>
<input type="reset" value="Clear" />
</p>
</fieldset>
</form>
</div>
<script src="js/calculatorscript.js"></script>
HomeRecipesTipsFAQ
</body>
</html>

How to calculate percentage with simple JavaScript code

I have already created a form in html and linked it with my style sheet and also JavaScript page.
My problem is displaying the result on the form.
Can someone please take a look at the JavaScript code and tell me what I am doing wrong?
See the snippet for more details
// Percentage Calculator
const myForm = document.getElementById('my-form');
myForm.onsubmit = e=>e.preventDefault() // disable form submit
;
myForm.oninput = percentageCalculator;
function percentageCalculator(amount, percent) {
return ((percent *amount) / 100).toFixed(2)
}
myForm.result.value = percentageCalculator()
fieldset { margin-top: 1em;
}
label {
display: inline-block; width: 8em; text-align: left;
}
input {
font-size: .8em; text-align: left; display: inline-block; width: 8em;
}
output::before {
content: '';
}
output {
font-weight: bold; width: 16em; border-bottom: 1px solid lightgrey; display: block; margin: .8em; float: right; text-align: right;
}
<h2>Percentage Calculator</h2>
<form action="" id="my-form">
<fieldset>
<legend>Calculate Percentage :</legend>
<append>What is <input type="number" name="percent" step=any min=0> % of </append>
<label><input type="number" class="amount" step=any min=0></label>
</fieldset>
<fieldset><br>
<legend>Result :</legend>
<output name="result" value='0'></output>
<br><br>
<button type="reset">Reset Calculator!</button>
</fieldset>
</form>
If you want to make result instantly on click of the input boxes then, make addEventListerner to input elements then get the value inside percentageCalculator and make calculation accordingly..
I have not modified anything from your HTML and only modified the JS part..
const myForm = document.getElementById('my-form');
const percent = document.querySelector('[name="percent"]');
const amount = document.querySelector('.amount');
const result = document.querySelector('[name="result"]');
function percentageCalculator() {
result.value = ((percent.value * amount.value) / 100).toFixed(2)
}
myForm.addEventListener('submit', e=>e.preventDefault())
myForm.addEventListener('input', percentageCalculator)
// myForm.result.value = percentageCalculator()
fieldset { margin-top: 1em;
}
label {
display: inline-block; width: 8em; text-align: left;
}
input {
font-size: .8em; text-align: left; display: inline-block; width: 8em;
}
output::before {
content: '';
}
output {
font-weight: bold; width: 16em; border-bottom: 1px solid lightgrey; display: block; margin: .8em; float: right; text-align: right;
}
<h2>Percentage Calculator</h2>
<form action="" id="my-form">
<fieldset>
<legend>Calculate Percentage :</legend>
<append>What is <input type="number" name="percent" step=any min=0> % of </append>
<label><input type="number" class="amount" step=any min=0></label>
</fieldset>
<fieldset><br>
<legend>Result :</legend>
<output name="result" value='0'></output>
<br><br>
<button type="reset">Reset Calculator!</button>
</fieldset>
</form>
If it is possible for you to modify HTML template then you can add name attribute to the amount input as well then you can get the element with myForm.inputName..
Alternative solution: https://codepen.io/Maniraj_Murugan/pen/KKpdgXo
Use oninput as I did below. Also give the amount input field a name. it's missing in the OP.
// Percentage Calculator
const myForm = document.getElementById('my-form');
myForm.oninput = () => {
myForm.result.value = percentageCalculator(myForm.amount.value, myForm.percent.value);
}
function percentageCalculator(amount, percent) {
return ((percent * amount) / 100).toFixed(2)
}
fieldset { margin-top: 1em;
}
label {
display: inline-block; width: 8em; text-align: left;
}
input {
font-size: .8em; text-align: left; display: inline-block; width: 8em;
}
output::before {
content: '';
}
output {
font-weight: bold; width: 16em; border-bottom: 1px solid lightgrey; display: block; margin: .8em; float: right; text-align: right;
}
<h2>Percentage Calculator</h2>
<form action="" id="my-form">
<fieldset>
<legend>Calculate Percentage :</legend>
<append>What is <input type="number" name="percent" step=any min=0> % of </append>
<label><input type="number" name="amount" class="amount" step=any min=0></label>
</fieldset>
<fieldset><br>
<legend>Result :</legend>
<output name="result" value='0'></output>
<br>
<button type="reset">Reset Calculator!</button>
</fieldset>
</form>
Pass the parameters into the function as a local scope and return the result back.
function percentageCalculator(amount,percent) {
return ((percent *amount) / 100).toFixed(2)
}
myForm.result.value = percentageCalculator()
// Percentage Calculator
const calculatedResult = document.getElementById('result');
function mySubmitFunction(e) {
e.preventDefault();
const percent = document.getElementById('percent').value;
const amount = document.getElementById('amount').value;
calculatedResult.value = percentageCalculator(amount,percent);
return false;
}
function percentageCalculator(amount,percent) {
return ((percent *amount) / 100).toFixed(2)
}
fieldset { margin-top: 1em;
}
label {
display: inline-block; width: 8em; text-align: left;
}
input {
font-size: .8em; text-align: left; display: inline-block; width: 8em;
}
output::before {
content: '';
}
output {
font-weight: bold; width: 16em; border-bottom: 1px solid lightgrey; display: block; margin: .8em; float: right; text-align: right;
}
<h2>Percentage Calculator</h2>
<form action="" onsubmit="return mySubmitFunction(event)" id="my-form">
<fieldset>
<legend>Calculate Percentage :</legend>
<append>What is <input type="number" id="percent" name="percent" step=any min=0> % of </append>
<label><input type="number" id="amount" class="amount" step=any min=0></label>
</fieldset>
<fieldset><br>
<legend>Result :</legend>
<output id="result" name="result" value='0'></output>
<br><br>
<button type="submit">Calculate!</button>
</fieldset>
</form>
Your mistake:
Submit button instead of reset
Prevent default once it's submitted
reference element using ID

Using CSS animation (transition) with onClick event

I'm trying to make a simple button btnAdd that changes one of my new div class so that it makes it visible and at a later date i'll add a cancel button that makes the same div hidden again, however I wanted to do this using animation so I'm trying to use transition: height 1s. But for some reason I can't seem to be able to get it working. Does anyone know where I'm going wrong here?
Thanks in advance,
Matt.
function open_Add_Menu() {
document.getElementById("new").className = "open";
}
p {
margin: 0;
}
body {
margin: 0;
background-color: #f6f4fb;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
color: #666;
}
.btnAdd {
width: 160px;
height: 30px;
float: right;
margin: 0px 30px 0px 0px;
background-color: #2f8fcb;
border: 2px solid #2f8fcb;
border-radius: 3px;
color: #fff;
font-weight: bold;
}
#new {
width: 50%;
height: 0;
margin: 30px 45% 10px 5%;
transition: height 1s;
overflow: hidden;
}
#new.open {
height: 400px;
}
<form>
<div id="btnAdd">
<button class="btnAdd" onclick="open_Add_Menu()">Add New</button>
</div>
<div id="new">
<div id="new_name">
<p>Name:</p>
<input type="text" id="name_tb" autocomplete="off">
</div>
<div id="new_add1">
<p>Address Line 1:</p>
<input type="text" id="add1_tb" autocomplete="off">
</div>
<div id="new_add2">
<p>Address Line 2:</p>
<input type="text" id="add2_tb" autocomplete="off">
</div>
<div id="new_add3">
<p>Address Line 3:</p>
<input type="text" id="add3_tb" autocomplete="off">
</div>
<div id="new_post">
<p>Postcode:</p>
<input type="text" id="post_tb" autocomplete="off">
</div>
<div id="new_number">
<p>Contact Number:</p>
<input type="text" id="number_tb" autocomplete="off">
</div>
</div>
</form>
You've done the right thing. The only problem is your button is placed within a form element. Once you click on that button, the form is being submitted.
To fix it, you can replace button by another tag. Or avoid submitting while click event happens.
You have to use classList.add to add a class in vanilla JS.
function open_Add_Menu() {
document.getElementById("new").classList.add('open');
}
p {
margin: 0;
}
body {
margin: 0;
background-color: #f6f4fb;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
color: #666;
}
.btnAdd {
width: 160px;
height: 30px;
float: right;
margin: 0px 30px 0px 0px;
background-color: #2f8fcb;
border: 2px solid #2f8fcb;
border-radius: 3px;
color: #fff;
font-weight: bold;
}
#new {
width: 50%;
height: 0;
margin: 30px 45% 10px 5%;
transition: height 1s;
overflow: hidden;
}
#new.open {
height: 400px;
}
<div>
<div id="btnAdd">
<button class="btnAdd" onclick="open_Add_Menu()">Add New</button>
</div>
<div id="new">
<div id="new_name">
<p>Name:</p>
<input type="text" id="name_tb" autocomplete="off">
</div>
<div id="new_add1">
<p>Address Line 1:</p>
<input type="text" id="add1_tb" autocomplete="off">
</div>
<div id="new_add2">
<p>Address Line 2:</p>
<input type="text" id="add2_tb" autocomplete="off">
</div>
<div id="new_add3">
<p>Address Line 3:</p>
<input type="text" id="add3_tb" autocomplete="off">
</div>
<div id="new_post">
<p>Postcode:</p>
<input type="text" id="post_tb" autocomplete="off">
</div>
<div id="new_number">
<p>Contact Number:</p>
<input type="text" id="number_tb" autocomplete="off">
</div>
</div>
</div>
Add the attribute type='button' to your button element. It should works for you.
<button type="button" class="btnAdd" onclick="open_Add_Menu()">Add New</button>
you can use the atribute visibility:
document.getElementById("myP").style.visibility = "hidden";
You can start the div with visibility hidden and remove that for showing the element.
Its works fine :)

How can I make my javascript form reset button work?

I want to reset my value inputs, Calculated Grade and also getElementById("an"), getElementById("and"). I've been trying various different methods and nothing seems to work. I also tried using forms method and my code seems to crash.
please help!
I have the following code(everything works except for reset button):
document.getElementById("button").onclick = function() {
var a = document.getElementById("1").value * 0.4;
var b = document.getElementById("2").value * 0.4;
var c = document.getElementById("3").value * 0.2;
var grade = a + b + c;
document.getElementById("ans").innerHTML = grade;
if (grade < 70) {
document.getElementById("and").innerHTML = "bad"
} else if (grade >= 70) {
document.getElementById("an").innerHTML = "good"
}
document.div[1].addEventListener('reset', function() {
document.getElementById('and', 'an', 'ans').innerHTML = '';
});
}
.legend {
position: relative;
width: 100%;
display: block;
padding: 20px;
border-radius: 20px;
background: #FFFF50;
padding: 15px;
color: black;
font-size: 20px;
font-family: 'Open Sans', sans-serif;
}
.wrapper {
border: 1px dashed #95a5a6;
height: 56px;
margin-top: 16px;
border-radius: 4px;
position: relative;
font-size: 20px;
}
.wrapper p {
line-height: 31px;
}
<div id="thing">
<legend class="legend">Average/Mean Calculator</legend>
<div id="myForm">
<p>
What's Your First Grade?<input type="text" id="1" placeholder="Input 1st #"><br> What About Your Second Grade? <input type="text" id="2" placeholder="Input 2st #"><br> And Third? <input type="text" id="3" placeholder="Almost there 3rd #">
</p>
<button id="button">Calculate</button>
<button onclick="myFunction()">Reset</button>
</div>
<p>
Calculated Grade: <span id="ans" style="color: green;"></span>
</p>
<div class="wrapper">
<p> <span id="an" style="color: green;"></span> <span id="and" style="color: red;"></span></p>
</div>
</div>
Define your myFunction:
function myFunction(){
document.getElementById('and','an','ans').innerHTML = '';
}
Add calculate as a function instead of adding onclick event listener to each button in page.
<button id="button" onclick="calculate()">Calculate</button>
getElementById() only supports one name at a time and only returns a single node not an array of nodes.
<!DOCTYPE html>
<html>
<body>
<style>
.legend {
position: relative;
width: 100%;
display: block;
padding: 20px;
border-radius: 20px;
background: #FFFF50;
padding: 15px;
color: black;
font-size: 20px;
font-family: 'Open Sans', sans-serif;
}
.wrapper {
border: 1px dashed #95a5a6;
height: 56px;
margin-top: 16px;
border-radius: 4px;
position: relative;
font-size: 20px;
}
.wrapper p {
line-height: 31px;
}
</style>
<div id="thing">
<legend class="legend">Average/Mean Calculator</legend>
<div id="myForm">
<p>
What's Your First Grade?<input type="text" id="1" placeholder="Input 1st #"><br> What About Your Second Grade? <input type="text" id="2" placeholder="Input 2st #"><br> And Third? <input type="text" id="3" placeholder="Almost there 3rd #">
</p>
<button id="button" onclick="calculate()">Calculate</button>
<button onclick="myFunction()">Reset</button>
</div>
<p>
Calculated Grade: <span id="ans" style="color: green;"></span>
</p>
<div class="wrapper">
<p> <span id="an" style="color: green;"></span> <span id="and" style="color: red;"></span></p>
</div>
</div>
<script>
function calculate() {
var a = document.getElementById("1").value * 0.4;
var b = document.getElementById("2").value * 0.4;
var c = document.getElementById("3").value * 0.2;
var grade = a + b + c;
document.getElementById("ans").innerHTML = grade;
if (grade < 70) {
document.getElementById("and").innerHTML = "bad"
} else if (grade >= 70) {
document.getElementById("an").innerHTML = "good"
}
}
function myFunction() {
document.getElementById('and').innerHTML = '';
document.getElementById("ans").innerHTML = '';
document.getElementById("an").innerHTML = '';
}
</script>
</body>
</html>
Try this function I hope it May work.
function myFunction(){
document.getElementById("1").value=0;
document.getElementById("2").value=0;
document.getElementById("3").value=0;
document.getElementById('ans').innerHTML = "0";
document.getElementById('and').innerHTML = '';
document.getElementById('an').innerHTML = '';
}
I would suggest to change your html to have a form for example
<div id="thing">
<legend class="legend">Average/Mean Calculator</legend>
<form id="myForm">
<p>
What's Your First Grade?
<input type="text" id="1" placeholder="Input 1st #" />
<br/> What About Your Second Grade?
<input type="text" id="2" placeholder="Input 2st #" />
<br/> And Third?
<input type="text" id="3" placeholder="Almost there 3rd #" />
</p>
<button id="button">Calculate</button>
<button onclick="myFunction()">Reset</button>
</form>
<div class="answer">
<p>Calculated Grade:
<span id="ans" style="color: green;"></span>
</p>
<div class="wrapper">
<p>
<span id="an" style="color: green;"></span>
<span id="and" style="color: red;"></span>
</p>
</div>
</div>
</div>
Then you can use form reset in javascript as follow:
function calculate() {
document.getElementById('myForm').reset();
}

Categories