First off what changed is I added two new divs and assigned it an id class of "order" and one "menuOutput". Ever since then my CSS within the div id="menuOutput" has disappeared. How do I get my CSS styles back whilst not changing how my js code works? I know the new additions of the div are the problem but please tell me how to keep my styles with the new code?
<body>
<div id="order"></div>
<div id="menuOutput">
<h1 class="menu">Menu</h1>
<div class="grid">
<div class="two">
<h2>Pizza by the slice ($2)</h2>
<input type="number" id="qty_slice of pizza">
<h2>Toppings</h2>
<p class="titles">Per Pepperoni($0.25):</p> <input type="number" id="qty_pepperoni">
<p class="titles">Per Meatball($0.35):</p> <input type="number" id="qty_meatballs">
<p class="titles">Per Mushhroom($0.40):</p> <input type="number" id="qty_mushrooms">
<p class="titles">Per Olive($0.20):</p> <input type="number" id="qty_olives">
</div>
<div class="one">
<h2>Sides</h2>
<p class="titles">Potato Salad($1.25):</p> <input type="number" id="qty_potato salad">
<p class="titles">Humus($2.50):</p> <input type="number" id="qty_hummus">
<p class="titles">Caesar Salad($3.50):</p> <input type="number" id="qty_caesar salad">
<p class="titles">Garden Salad($2.25):</p> <input type="number" id="qty_garden salad">
</div>
<div class="three">
<h2>Drinks</h2>
<div>
<p class="titles">Small Soda($1.95):</p> <input type="number" id="qty_small">
<p class="titles">Medium Soda($2.20):</p> <input type="number" id="qty_medium">
<p class="titles">Large Soda($2.50):</p> <input type="number" id="qty_large">
</div><hr>
<p class="titles">Juice($2.00):</p> <input type="number" id="qty_juice">
<p class="titles">Water($1.25):</p> <input type="number" id="qty_water">
</div>
</div><br>
</div>
<div class="button">
<button type class="button" id="submitOrder">Review Order</button>
</div>
<div id="order"></div>
<script src="./run.js"></script>
</body>
------------------------------------JS---------------------------
//get menu from api
var getJSON = function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
callback(null, xhr.response);
} else {
callback(status);
}
};
xhr.send();
};
/*
{
"menu": {
"slice of pizza": "2.00",
qty_slice of pizza
"toppings": {
"pepperoni": ".25",
"meatballs": ".35",
"mushrooms": ".40",
"olives": ".20"
},
"sides": {
"potato salad": "1.25",
"hummus": "2.50",
"caesar salad": "3.50",
"garden salad": "2.25"
},
"drinks": {
"soda": {
"small": "1.95",
"medium": "2.20",
"large": "2.50"
},
"juice": "2.00",
"water": "1.25"
}
}
}
*/
getJSON('https://mm214.com/menu.php', function(err, data) {
if (err != null) {
alert('Something went wrong: ' + err);
} else {
var content = '';
for (x in data.menu){
if (typeof(data.menu[x]) == 'object'){
for (y in data.menu[x]) {
if (typeof(data.menu[x][y]) == 'object'){
for (z in data.menu[x][y]) {
content += z + ':' + data.menu[x][y][z] + '<input type="number" id = "qty_' + z + '"><br>';
}
}
else {
content += y + ':' + data.menu[x][y] + '<input type="number" id = "qty_' + y + '"><br>';
}
}//closes y in data
}
else
{
content += x + ':' + data.menu[x] + '<input type="number" id = "qty_' + x + '"><br>';
}//else for data.menu[x] if not an object
}
}//closes outer for loop
//localStorage only stores strings! Stringify turns objects into strings!
//parse converts JSON strings to objects that can be looped around
document.getElementById("menuOutput").innerHTML = content;
localStorage.setItem('order',JSON.stringify(data));
console.log(a + ':' + order[a]);
var order = JSON.parse(localStorage.getItem('order'));
console.log(typeof(order));
for (a in order){
}
});
function storeOrder(){
var pizzaqty = document.getElementById('qty_slice of pizza').value;
localStorage.setItem('pizza',pizzaqty);
var price = pizzaqty * 2;
}
function retrieveOrder(){
var pizzaordered = localStorage.getItem('pizza');
}
//output html
//
//document.getElementById("menuOutput").innerHTML = "Here is the menu: <br>" + data.menu;
//why in't this working?
//style menu for ordering
//save order as json string
//save in local storage
//your order button
//onclick: show order
document.getElementById('order').innerHTML = localStorage.getItem('order1');
------------------CSS------------------------------
#import url('https://fonts.googleapis.com/css2?
family=Bangers&family=Bree+Serif&family=Chelsea+Market&family=Oswald:wght#300&display=swap');
.grid {
display: grid;
grid-template-areas:
"one two three"
"one two three"
"one two three";
grid-template-columns: 1fr 2fr 1fr;
grid-template-rows: repeat(3, 165px);
}
.title {
font-family: 'Chelsea Market', cursive;
font-size: 30px;
text-align: center;
color: teal;
}
input[type="number"] {
width: 40px;
}
.menu {
text-align: center;
}
.button {
text-align: center;
font-family: 'Bangers', cursive;
font-size: 25px;
}
.titles {
font-family: 'Bree Serif', serif;
}
.pizza {
text-align: center;
color: tomato;
background-color: teal;
}
.one {
grid-area: one;
background-color: #008c45;
text-align: center;
}
.two {
text-align: center;
grid-area: two;
background-color: #f4f5f0;
color: black;
}
.three {
grid-area: three;
text-align: center;
background-color: #cd212a;
}
h2 {
font-size: 30px;
font-family: 'Oswald', sans-serif;
text-align: center;
}
The issue, I suspect is this line:
document.getElementById("menuOutput").innerHTML = content;
This basically says everything between the div with id "menuOutput" should now be the html in your content variable.
But nowhere in your content variable are you specifying the .grid, .one, .two, .three div classes.
Inspect the source code of the page: does <div class="two"> exist?
First of all, remember you can't have two identical ids in one page so you have to remove one of divs with id=order (I removed the one at the top). second, it seems you have added your classes in id attribute. we have two attributes for each element, id and class. you can add multiple classes for one element (e.g class="green blue red"), but you must have only one id which is unique in your page and can't include white spaces. (e.g id="blue_red"). at the end, I edited your code and removed the pizza from id and add it to the class and also corrected the values you have assigned to the elements and your css works fine again. you can run the snippet to see the result. wish it helps you:)
#import url('https://fonts.googleapis.com/css2?family=Bangers&family=Bree+Serif&family=Chelsea+Market&family=Oswald:wght#300&display=swap');
.grid {
display: grid;
grid-template-areas:
"one two three"
"one two three"
"one two three";
grid-template-columns: 1fr 2fr 1fr;
grid-template-rows: repeat(3, 165px);
}
.title {
font-family: 'Chelsea Market', cursive;
font-size: 30px;
text-align: center;
color: teal;
}
input[type="number"] {
width: 40px;
}
.menu {
text-align: center;
}
.button {
text-align: center;
font-family: 'Bangers', cursive;
font-size: 25px;
}
.titles {
font-family: 'Bree Serif', serif;
}
.pizza {
text-align: center;
color: tomato;
background-color: teal;
}
.one {
grid-area: one;
background-color: #008c45;
text-align: center;
}
.two {
text-align: center;
grid-area: two;
background-color: #f4f5f0;
color: black;
}
.three {
grid-area: three;
text-align: center;
background-color: #cd212a;
}
h2 {
font-size: 30px;
font-family: 'Oswald', sans-serif;
text-align: center;
}
<div id="menuOutput">
<h1 class="menu">Menu</h1>
<div class="grid">
<div class="two">
<h2>Pizza by the slice ($2)</h2>
<input type="number" class="pizza" id="qty_slice_of_pizza">
<h2>Toppings</h2>
<p class="titles">Per Pepperoni($0.25):</p> <input type="number" id="qty_pepperoni">
<p class="titles">Per Meatball($0.35):</p> <input type="number" id="qty_meatballs">
<p class="titles">Per Mushhroom($0.40):</p> <input type="number" id="qty_mushrooms">
<p class="titles">Per Olive($0.20):</p> <input type="number" id="qty_olives">
</div>
<div class="one">
<h2>Sides</h2>
<p class="titles">Potato Salad($1.25):</p> <input type="number" class="salad" id="qty_potato_salad">
<p class="titles">Humus($2.50):</p> <input type="number" class="salad" id="qty_hummus">
<p class="titles">Caesar Salad($3.50):</p> <input type="number" class="salad" id="qty_caesar_salad">
<p class="titles">Garden Salad($2.25):</p> <input type="number" class="salad" id="qty_garden_salad">
</div>
<div class="three">
<h2>Drinks</h2>
<div>
<p class="titles">Small Soda($1.95):</p> <input type="number" id="qty_small">
<p class="titles">Medium Soda($2.20):</p> <input type="number" id="qty_medium">
<p class="titles">Large Soda($2.50):</p> <input type="number" id="qty_large">
</div>
<hr/>
<p class="titles">Juice($2.00):</p> <input type="number" id="qty_juice">
<p class="titles">Water($1.25):</p> <input type="number" id="qty_water">
</div>
</div>
<br/>
</div>
<div class="button">
<button type class="button" id="submitOrder">Review Order</button>
</div>
<div id="order"></div>
The root cause of the problem is due to the div tags getting mixed up.
Here are the steps to resolve the problem:
Move the div tag meant for menu-output to the bottom of the page and add closure to it immediately.
Remove the duplicate div tags with same ID (menuOutput, order).
Here is the working example with the div tags adjusted and duplicate divs removed:
<html>
<head>
<title>Menu - demo</title>
<style>
#import url('https://fonts.googleapis.com/css2?family=Bangers&family=Bree+Serif&family=Chelsea+Market&family=Oswald:wght#300&display=swap');
.grid {
display: grid;
grid-template-areas:
"one two three"
"one two three"
"one two three";
grid-template-columns: 1fr 2fr 1fr;
grid-template-rows: repeat(3, 165px);
}
.title {
font-family: 'Chelsea Market', cursive;
font-size: 30px;
text-align: center;
color: teal;
}
input[type="number"] {
width: 40px;
}
.menu {
text-align: center;
}
.button {
text-align: center;
font-family: 'Bangers', cursive;
font-size: 25px;
}
.titles {
font-family: 'Bree Serif', serif;
}
.pizza {
text-align: center;
color: tomato;
background-color: teal;
}
.one {
grid-area: one;
background-color: #008c45;
text-align: center;
}
.two {
text-align: center;
grid-area: two;
background-color: #f4f5f0;
color: black;
}
.three {
grid-area: three;
text-align: center;
background-color: #cd212a;
}
h2 {
font-size: 30px;
font-family: 'Oswald', sans-serif;
text-align: center;
}
</style>
</head>
<body>
<div id="order">
<h1 class="menu">Menu</h1>
<div class="grid">
<div class="two">
<h2>Pizza by the slice ($2)</h2>
<input type="number" id="qty_slice_of_pizza" />
<h2>Toppings</h2>
<p class="titles">Per Pepperoni($0.25):</p>
<input type="number" id="qty_pepperoni">
<p class="titles">Per Meatball($0.35):</p>
<input type="number" id="qty_meatballs">
<p class="titles">Per Mushroom($0.40):</p>
<input type="number" id="qty_mushrooms">
<p class="titles">Per Olive($0.20):</p>
<input type="number" id="qty_olives">
</div>
<div class="one">
<h2>Sides</h2>
<p class="titles">Potato Salad($1.25):</p>
<input type="number" id="qty_potato_salad">
<p class="titles">Humus($2.50):</p>
<input type="number" id="qty_hummus">
<p class="titles">Caesar Salad($3.50):</p>
<input type="number" id="qty_caesar_salad">
<p class="titles">Garden Salad($2.25):</p>
<input type="number" id="qty_garden_salad">
</div>
<div class="three">
<h2>Drinks</h2>
<p class="titles">Small Soda($1.95):</p>
<input type="number" id="qty_small">
<p class="titles">Medium Soda($2.20):</p>
<input type="number" id="qty_medium">
<p class="titles">Large Soda($2.50):</p>
<input type="number" id="qty_large">
<p class="titles">Juice($2.00):</p>
<input type="number" id="qty_juice">
<p class="titles">Water($1.25):</p>
<input type="number" id="qty_water">
</div>
</div>
<br>
</div>
<div class="button">
<button type="button" id="submitOrder">Review Order</button>
</div>
<div id="menuOutput"></div>
<script>
//get menu from api
var getJSON = function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
callback(null, xhr.response);
} else {
callback(status);
}
};
xhr.send();
};
getJSON('https://mm214.com/menu.php', function(err, data) {
if (err != null) {
alert('Something went wrong: ' + err);
} else {
var content = '';
for (x in data.menu){
if (typeof(data.menu[x]) == 'object'){
for (y in data.menu[x]) {
if (typeof(data.menu[x][y]) == 'object'){
for (z in data.menu[x][y]) {
content += z + ':' + data.menu[x][y][z] + '<input type="number" id = "qty_' + z + '"><br>';
}
}
else {
content += y + ':' + data.menu[x][y] + '<input type="number" id = "qty_' + y + '"><br>';
}
}//closes y in data
}
else
{
content += x + ':' + data.menu[x] + '<input type="number" id = "qty_' + x + '"><br>';
}//else for data.menu[x] if not an object
}
}//closes outer for loop
//localStorage only stores strings! Stringify turns objects into strings!
//parse converts JSON strings to objects that can be looped around
document.getElementById("menuOutput").innerHTML = content;
localStorage.setItem('order',JSON.stringify(data));
console.log(a + ':' + order[a]);
var order = JSON.parse(localStorage.getItem('order'));
console.log(typeof(order));
for (a in order){
}
});
function storeOrder(){
var pizzaqty = document.getElementById('qty_slice of pizza').value;
localStorage.setItem('pizza',pizzaqty);
var price = pizzaqty * 2;
}
function retrieveOrder(){
var pizzaordered = localStorage.getItem('pizza');
}
</script>
</body>
</html>
Output:
Related
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>
So I have made a function which changes my values in a "cart". Every input field has their one value and this is added or substracted on it's total on change of the input field. It looks like this:
And my code looks like this (yes I am gonna cleanup the html+css later, this is just for testing :-):
var extraValues = document.querySelectorAll("input[type=number]");
var extraTotal = 0;
Array.prototype.forEach.call(extraValues, function (extraValue) {
extraValue.addEventListener('change', function() {
var getExtraId = extraValue.id;
var extraLength = getExtraId.length;
var currentExtra = getExtraId.charAt(extraLength - 1);
var catId = "testKassabon" + currentExtra;
var extraSort = extraValue.parentElement.querySelector('label');
var extraPrice = extraValue.parentElement.querySelector('.extraPrice').innerText;
var totalPrice = extraPrice * this.value;
var showExtra = document.getElementById(catId);
showExtra.innerHTML = "<div style='display: flex; justify-content: space-between; margin-top: 10px;'><div>" + this.value + "x " + extraSort.innerText + "</div><div style='color: #EC008C; font-weight: 700; font-size: 16px;'>€ " + totalPrice + "</div></div>";
})
});
.col-form-label {
font-weight: 700;
display: block;
width: 100%;
padding-bottom: 5px;
}
<div style="display: flex; justify-content: space-between; max-width: 600px;">
<div>
<div class="item" style="width: 200px; margin-bottom: 20px;">
<span class="extraPrice" style="display: none;">7.50</span>
<label class="col-form-label" style="font-weight: 700;">3-gangendiner</label>
<input type="number" id="extra1" class="form-control" style="max-width: 70px;" value="0" min="0">
</div>
<div class="item" style="width: 200px; margin-bottom: 20px;">
<span class="extraPrice" style="display: none;">10</span>
<label class="col-form-label">Fietshuur</label>
<input type="number" id="extra2" class="form-control" style="max-width: 70px;" value="0" min="0">
</div>
<div class="item" style="width: 200px; margin-bottom: 20px;">
<span class="extraPrice" style="display: none;">2.50</span>
<label class="col-form-label">Uitgebreid ontbijtbuffet</label>
<input type="number" id="extra3" class="form-control" style="max-width: 70px;" value="0" min="0">
</div>
</div>
<div style="max-width: 300px; width: 100%; padding: 20px; background-color: #F7F7F7; border-radius: 4px; margin: 0px;">
<span style="color: #000; font-weight: 700; font-size: 20px; padding-bottom: 10px; display: block;">Uw totaalprijs</span>
<div style="display: flex; flex-direction: column; height: 100%; padding-bottom: 40px;">
<div id="testKassabon1"></div>
<div id="testKassabon2"></div>
<div id="testKassabon3" style="flex-grow: 1;"></div>
<div id="totalPrice"></div>
</div>
</div>
</div>
This works perfectly. But now I need to calculate the total amount of these 3 values each time one of the inputs changes, and show it in id="totalPrice". I have NO idea how to do this, since everytime I try this it just replaced the total pricing instead of adding or substracting it from the total. Does anyone know how to do this?
Try this Code man thanks :-)
function countProperties(obj) {
var count = 0;
for(var prop in obj) {
console.log(prop,obj)
if(obj.hasOwnProperty(prop))
count = count +obj[prop];
}
return count;
}
var total = {}
var extraValues = document.querySelectorAll("input[type=number]");
var extraTotal = 0;
Array.prototype.forEach.call(extraValues, function (extraValue) {
extraValue.addEventListener('change', function() {
var getExtraId = extraValue.id;
var extraLength = getExtraId.length;
var currentExtra = getExtraId.charAt(extraLength - 1);
var catId = "testKassabon" + currentExtra;
var extraSort = extraValue.parentElement.querySelector('label');
var extraPrice = extraValue.parentElement.querySelector('.extraPrice').innerText;
var totalPrice = extraPrice * this.value;
total[catId] = totalPrice
// var TotalCost = Object.values(total).reduce((a, b) //=> a + b, 0)
var TotalCost = countProperties(total)
console.log(TotalCost)
alert(TotalCost)
var showExtra = document.getElementById(catId);
showExtra.innerHTML = "<div style='display: flex; justify-content: space-between; margin-top: 10px;'><div>" + this.value + "x " + extraSort.innerText + "</div><div style='color: #EC008C; font-weight: 700; font-size: 16px;'>€ " + totalPrice + "</div></div>";
})
});
.col-form-label {
font-weight: 700;
display: block;
width: 100%;
padding-bottom: 5px;
}
<div style="display: flex; justify-content: space-between; max-width: 600px;">
<div>
<div class="item" style="width: 200px; margin-bottom: 20px;">
<span class="extraPrice" style="display: none;">7.50</span>
<label class="col-form-label" style="font-weight: 700;">3-gangendiner</label>
<input type="number" id="extra1" class="form-control" style="max-width: 70px;" value="0" min="0">
</div>
<div class="item" style="width: 200px; margin-bottom: 20px;">
<span class="extraPrice" style="display: none;">10</span>
<label class="col-form-label">Fietshuur</label>
<input type="number" id="extra2" class="form-control" style="max-width: 70px;" value="0" min="0">
</div>
<div class="item" style="width: 200px; margin-bottom: 20px;">
<span class="extraPrice" style="display: none;">2.50</span>
<label class="col-form-label">Uitgebreid ontbijtbuffet</label>
<input type="number" id="extra3" class="form-control" style="max-width: 70px;" value="0" min="0">
</div>
</div>
<div style="max-width: 300px; width: 100%; padding: 20px; background-color: #F7F7F7; border-radius: 4px; margin: 0px;">
<span style="color: #000; font-weight: 700; font-size: 20px; padding-bottom: 10px; display: block;">Uw totaalprijs</span>
<div style="display: flex; flex-direction: column; height: 100%; padding-bottom: 40px;">
<div id="testKassabon1"></div>
<div id="testKassabon2"></div>
<div id="testKassabon3" style="flex-grow: 1;"></div>
<div id="totalPrice"></div>
</div>
</div>
</div>
Solution
In this solution I have added a function to calculate the sum.
So when the value changes then I call at the end of your function.
The calculator which calculates the sum and insert it inside your text field.
var extraValues = document.querySelectorAll("input[type=number]");
// extraValues.forEach((elem)=>{
// elem.addEventListener('input', function (evt) {
// calculator();
// })
// });
Array.prototype.forEach.call(extraValues, function (extraValue) {
extraValue.addEventListener('change', function() {
var getExtraId = extraValue.id;
var extraLength = getExtraId.length;
var currentExtra = getExtraId.charAt(extraLength - 1);
var catId = "testKassabon" + currentExtra;
var extraSort = extraValue.parentElement.querySelector('label');
var extraPrice = extraValue.parentElement.querySelector('.extraPrice').innerText;
var totalPrice = extraPrice * this.value;
var showExtra = document.getElementById(catId);
showExtra.innerHTML = "<div style='display: flex; justify-content: space-between; margin-top: 10px;'><div>" + this.value + "x " + extraSort.innerText + "</div><div style='color: #EC008C; font-weight: 700; font-size: 16px;'>€ " + totalPrice + "</div></div>";
calculator()
})
});
function calculator(){
let prices = document.querySelectorAll('.extraPrice')
let sum = 0;
let fac = 0;
extraValues.forEach((elem, ind) =>{
fac = parseFloat(prices[ind].innerHTML)
sum += parseInt(elem.value) * fac;
})
document.getElementById("totalPrice").innerHTML = sum;
}
.col-form-label {
font-weight: 700;
display: block;
width: 100%;
padding-bottom: 5px;
}
<div style="display: flex; justify-content: space-between; max-width: 600px;">
<div>
<div class="item" style="width: 200px; margin-bottom: 20px;">
<span class="extraPrice" style="display: none;">7.50</span>
<label class="col-form-label" style="font-weight: 700;">3-gangendiner</label>
<input type="number" id="extra1" class="form-control" style="max-width: 70px;" value="0" min="0">
</div>
<div class="item" style="width: 200px; margin-bottom: 20px;">
<span class="extraPrice" style="display: none;">10</span>
<label class="col-form-label">Fietshuur</label>
<input type="number" id="extra2" class="form-control" style="max-width: 70px;" value="0" min="0">
</div>
<div class="item" style="width: 200px; margin-bottom: 20px;">
<span class="extraPrice" style="display: none;">2.50</span>
<label class="col-form-label">Uitgebreid ontbijtbuffet</label>
<input type="number" id="extra3" class="form-control" style="max-width: 70px;" value="0" min="0">
</div>
</div>
<div style="max-width: 300px; width: 100%; padding: 20px; background-color: #F7F7F7; border-radius: 4px; margin: 0px;">
<span style="color: #000; font-weight: 700; font-size: 20px; padding-bottom: 10px; display: block;">Uw totaalprijs</span>
<div style="display: flex; flex-direction: column; height: 100%; padding-bottom: 40px;">
<div id="testKassabon1"></div>
<div id="testKassabon2"></div>
<div id="testKassabon3" style="flex-grow: 1;"></div>
<div id="totalPrice"></div>
</div>
</div>
</div>
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
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>
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();
}