Learning javascript currently. I wanted to create a simple volume calculator for practice. It works at first when you click the button to calculate but if you change the numbers for the inputs it will not calculate unless refreshed.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="Calc.css">
</head>
<body>
<div class="box">
<input type="number" class="length">
<input type="number" class="width">
<input type="number" class="height">
<button type="button">calculate</button>
<p>Your volume is: <span type="number" class="volume"></span></p>
</div>
<script src="Calc.js"></script>
</body>
</html>
const length = document.querySelector('.length').value;
const width = document.querySelector('.width').value;
const height = document.querySelector('.height').value;
const button = document.querySelector('button');
const volume = document.querySelector('.volume');
function calculate () {
volume.innerHTML = length * width * height + " cubic inches.";
}
button.addEventListener('click', calculate);
Welcome to SO.
There was a tiny mistake you made there in JS. Instead of loading length, breadth and height in variable while loading JS file, you have to load these values everytime the button is clicked, i.e. everytime function is called. So just put those variable declaration inside function.
In nut shell,
From this:
const length = document.querySelector('.length').value;
const width = document.querySelector('.width').value;
const height = document.querySelector('.height').value;
const button = document.querySelector('button');
const volume = document.querySelector('.volume');
function calculate () {
volume.innerHTML = length * width * height + " cubic inches.";
}
button.addEventListener('click', calculate);
You will go to:
const button = document.querySelector('button');
const volume = document.querySelector('.volume');
function calculate () {
const length = document.querySelector('.length').value;
const width = document.querySelector('.width').value;
const height = document.querySelector('.height').value;
volume.innerHTML = length * width * height + " cubic inches.";
}
button.addEventListener('click', calculate);
Notice where I have put variable declaration.
Fetch values inside your function
const button = document.querySelector('button');
const volume = document.querySelector('.volume');
function calculate() {
const length = document.querySelector('.length').value;
const width = document.querySelector('.width').value;
const height = document.querySelector('.height').value;
volume.innerHTML = (length * width * height) + " cubic inches.";
}
button.addEventListener('click', calculate);
<div class="box">
<input type="number" class="length">
<input type="number" class="width">
<input type="number" class="height">
<button type="button">calculate</button>
<p>Your volume is: <span type="number" class="volume"></span></p>
</div>
` <input type="text" id="length">
<input type="text" id="width">
<input type="text" id="height">
<button type="button" id="myBtn">calculate</button>
<p>Your volume is: <span id="Answer"> </span></p>
<script>
function calculateVolume()
{
var width = document.getElementById("width");
var height = document.getElementById("height");
var length = document.getElementById("length");
var Answer = width * height *length
document.getElementById("Answer").innerHTML = Answer +"cubic inches.";
}
document.getElementById("myBtn").addEventListener("click", calculateVolume);
</script>
`
Related
I'm doing my Homework but I need help calculating the right way, the code I provided is what I have so far, and this is what my teacher requires: Create a webpage that contains the heading, Student Grades, and inputs a student's homework average, mid-term exam score, final exam score, and participation (all those grades will be entered as integers). Create a script that checks for valid input, i.e., that the input is between 0-100 and that, of course, the input are all numbers. If all input is valid then calculate and display the student's final average sorry for dumb question i started learning JS not to long ago
const answer = () => {
let hwNum = document.querySelector('#hwAverage');
let mtNum = document.querySelector('#midTerm');
let feNum = document.querySelector('#finalExam');
let partiNum = document.querySelector('#participation');
let answer = document.querySelector('#result')
n1 = Number(hwNum);
n2 = Number(mtNum);
n3 = Number(feNum);
n4 = Number(partiNum);
let result = (.5 * n1) + (.2 * n2) + (.2 * n3) + (.1 * n4)
answer.textContent = result
return result
};
let submit = document.querySelector('#submit').addEventListener('click', function() { answer() } )
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="part1.css">
<script src="part1.js" defer></script>
<title>part 1</title>
</head>
<body>
<header>
<h1>Part 1</h1>
</header>
<br>
<label for="hwAvg"><b>Enter</b> Homework Average : </label>
<input type="number" name="hwAverage" id="hwAverage" placeholder="Enter Number 0-100">
<br>
<label for="term"><b>Enter</b> Mid-term exam score : </label>
<input type="number" name="midTerm" id="midTerm" placeholder="Enter Number 0-100">
<br>
<label for="exam"><b>Enter</b> Final exam score : </label>
<input type="number" name="finalExam" id="finalExam" placeholder="Enter Number 0-100">
<br>
<label for="partic"><b>Enter</b> Participation : </label>
<input type="number" name="participation" id="participation" placeholder="Enter Number 0-100">
<br>
<br>
<input type="button" value="SUBMIT" id="submit" class="submit">
<br>
<br>
<label for="resultLabel">Result : </label>
<div class="result" id="result"></div>
<br>
<br>
<div class="rubric">
<div class="A-tier">
<p>90-100 | A</p>
</div>
<div class="B-tier">
<p>80-89 | B</p>
</div>
<div class="C-tier">
<p>70-79 | C</p>
</div>
<div class="D-tier">
<p>60-69 | D</p>
</div>
<div class="F-tier">
<p>0-59 | F</p>
</div>
</div>
</body>
</html>**strong text**
Your solution is good.
If you want to get the data from a input element you have to use the value property.
Example:
let hwNum = document.querySelector('#hwAverage').value;
But if you want to get a element for manipulate you don't use the value property.
Example:
let answer = document.querySelector('#result');
Then if you want to set a data a input element you have to use the value property again. Example:
let hwNum = document.querySelector('#hwAverage');
hwNum.value = 'new value';
for anothers elements set value or data
let answer = document.querySelector('#result');
answer.textContent = 'new data o value';
You need to get the value of following input fields. Try this.
let hwNum = document.querySelector('#hwAverage').value;
let mtNum = document.querySelector('#midTerm').value;
let feNum = document.querySelector('#finalExam').value;
let partiNum = document.querySelector('#participation').value;
let answer = document.querySelector('#result').value;
The result does not appear. I'm quite new so I do not know what to do. I want the volume/result to appear. The code I used is:
<html>
<head>
<title>Calculate Area</title>
</head>
<body>
<h2 style = "color:blue;">Calculating Volume Rectangle</h2>
Length: <input type = "text" id = 'length'><br>
<br>
Width: <input type = "text" id = "width"><br>
<br>
<input type = "submit" value = 'Calculate Area' onclick = "calculate()">
<p>The Volume of the Rectangle is:</p>
<p id="answer" style='color:red;'></p>
</body>
<script>
function calculate()
{
var length = document.getElementById("length').value;
var width = document.getElementById("width").value;
var height = document.getElementById("width").value;
var result = (length) * (width) * (height)
document.getElementById("answer").innerHTML = (result);
}
</script>
</html>
Find the entire solution below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Calculate Area</title>
</head>
<body>
<h2 style="color: blue">Calculating Volume Rectangle</h2>
Length: <input type="text" id="length" /><br />
<br />
Width: <input type="text" id="width" /><br />
<br />
Height: <input type="text" id="height" /><br />
<button style="margin-top: 10px" onclick="calculate()">Calculate</button>
<div style="display: flex">
<p>The Volume of the Rectangle is:</p>
<p id="answer" style="color: red; margin-left: 10px"></p>
</div>
</body>
<script>
function calculate() {
var length = document.getElementById('length').value;
var width = document.getElementById('width').value;
var height = document.getElementById('height').value;
var result = length * width * height;
document.getElementById('answer').innerHTML = result;
}
</script>
</html>
you have some missing =, " and ' in the code and also parse string values to int for multiply.
<html>
<head>
<title>Calculate Area</title>
</head>
<body>
<h2 style="color:blue;">Calculating Volume Rectangle</h2>
Length: <input type="text" id="length"><br>
<br>
Width: <input type="text" id="width"><br>
<br>
Height: <input type="text" id="height"><br>
<br>
<input type="submit" value='Calculate Area' onclick="calculate()"> <!-- always use brakets when you are calling to a function -->
<p>The Volume of the Rectangle is:</p>
<p id="answer"></p>
</body>
<script>
function calculate() {
var length = document.getElementById("length").value;
var width = document.getElementById("width").value;
var height = document.getElementById("height").value;
var result = parseInt(length) * parseInt(width) * parseInt(height); //convert extracted string values to integers
document.getElementById("answer").innerHTML = result;
}
</script>
</html>
I did some corrections, you can check it out on this link:
https://codesandbox.io/embed/strange-colden-w92gbw?fontsize=14&hidenavigation=1&theme=dark
But basically:
On line 15, you put an onClick but pass the value link a string calculate, pass an empty param calculate() in the onClick and in the function on line 21.
On line 22 at the end of var length theres a ("length').value, I changed to ("length").value;
I hope it can help you.
<h2 style = "color:blue;">Calculating Volume Rectangle</h2>
Length: <input type = "text" id ='length'><br>
<br>
Width: <input type="text" id="width"><br>
<br>
<input type="submit" value = 'Calculate Area' onclick = "calculate()">
<p>The Volume of the Rectangle is:</p>
<p id ="answer" style='color:red;'></p>
</body>
<script>
function calculate(){
var length = document.getElementById("length").value;
var width = document.getElementById("width").value;
var height = document.getElementById("width").value;
var result = (length) * (width) * (height)
document.getElementById("answer").innerHTML = (result);
}
</script>
Here is a list of the most relevant points concerning the many problems that plagues the OP code:
If you are using more than one form control (ex. <input>, <button>, <output>, etc), wrap everything in a <form>. Having a <form> allows you to use very useful interfaces:
HTMLFormElement
HTMLFormControlsCollection
Keep in mind, all HTML is basically strings. An htmlString is a string that can be parsed into HTML, all values of HTML attributes are strings, the only time when value of form controls are accessible real numbers is when it is extracted as a string then converted into a real number. There are a few ways to convert a string into a number:
.parseInt() method
.parseFloat() method
Number() constructor
* / - + operators by cohersion (+is used through out the example)
Finally, event delegation is used to handle the "input" Events on each <input> within the <form>. Also, do not use inline event attributes -- inline event handlers are garbage.
// Reference <form>
const calc = document.forms.calc;
// Register the "input" event to <form>
calc.oninput = calcDim;
// Event handler passes Event Object
function calcDim(e) {
/*
HTMLFormControlsCollection (all <input>, <button>, <output>, <fieldset>)
e.target references the element the user is currently typing into.
*/
const io = this.elements;
const active = e.target;
/*
If >active< [name="num"]...
...if >H< is [disabled] OR it's .value = 0...
...>result< .value = >L< * >W<...
...Otherwise >result< .value = >L< * >W< * >H<
*/
if (active.name === 'num') {
if (io.H.disabled === true || +io.H.value === 0) {
io.result.value = +io.L.value * +io.W.value;
} else {
io.result.value = +io.L.value * +io.W.value * +io.H.value;
}
}
/*
If >L< .value AND >W< .value are both greater than 0...
...>H< is not [disabled]...
...Otherwise >H< is [disabled]
*/
if (+io.L.value > 0 && +io.W.value > 0) {
io.H.disabled = false;
} else {
io.H.disabled = true;
}
/*
If >H< .value is greater than 0...
...The result <label> [data-dim] is 'Volume'...
...Otherwise it's 'Area'
*/
if (+io.H.value > 0) {
document.querySelector(`[for='result']`).dataset.dim = 'Volume';
} else {
document.querySelector(`[for='result']`).dataset.dim = 'Area';
}
};
*, *::before, *::after {box-sizing: border-box;}
html {font: 2.5ch/1.15 'Segoe UI'}
h1 {font-size: 1.6em; margin-bottom: 4px;}
h2 {font-size: 1.4em;}
fieldset {width: 30ch; padding-left: 25px;}
legend {margin: 0 0 1ch -1ch; font-size: 1.25rem;}
input, output {display: inline-block; width: 10ch; font: 2ch/1.15 Consolas; text-align: center}
label {display: inline-block; width: 8ch;}
[for='result']::before {content: attr(data-dim)}
[for='result']::after {content:': '}
#L {width: 10.05ch; margin-left: -1px;}
#result {margin-left: -8px;}
[disabled='true'] {opacity: 0.4;}
<!DOCTYPE html>
<html lang='en'>
<head>
<title></title>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<meta name='viewport' content='width=device-width, initial-scale=1, shrink-to-fit=no'>
<style>
/* CSS Block */
</style>
</head>
<body>
<header>
<h1>Area/Volume</h1>
<h2>Calculator</h2>
</header>
<main>
<form id='calc'>
<fieldset>
<legend>Length, Width, & Hieght</legend>
<label for='L'>Length: </label>
<input id='L' name='num' type='number' min='0' placeholder='0'><br>
<label for='W'>Width: </label>
<input id='W' name='num' type='number' min='0' placeholder='0'><br>
<label for='H'>Hieght: </label>
<input id='H' name='num' type='number' min='0' placeholder='0' disabled><br>
</fieldset>
<fieldset>
<label for='result' data-dim='Area'></label>
<output id='result'></output>
</fieldset>
</form>
</main>
<script>
/* Inline JavaScript */
</script>
</body>
</html>
Background -
I am new to JavaScript world and working on a small application to generate random number between a range. Two Inputs are taken by the user i.e. "minValue" and "maxValue" of the range and random number is generated by clicking on the "Generate" button.
Question -
How can I get the input from these two number fields when it gets updated again and again using vanilla JavaScript without any framework ?
I want to alert the user if they put the value vice versa before hitting generate button. Means if any user put minimum value in maxValue input and maximum value in minValue input. As soon as user stops I just want to make a alert for it. I know it can be done easily after hitting generate button but just for learning purpose I want to perform the operation this way.
Right now I am getting blank value of variable MinValue and maxValue at the beginning of the program and after that value is not updated by changing number field value.
const numberGenerator = document.querySelector(".random-number");
const button = document.querySelector(".button1");
const minValue = document.querySelector("#min").value;
const maxValue = document.querySelector("#max").value;
// console.log(numberGenerator);
// console.log(button);
//console.log(minValue);
//console.log(maxValue);
let generateRandomNumber = (max, min) => {
randomNumber = Math.floor(Math.random() * (max - min)) + min
numberGenerator.innerHTML = randomNumber;
};
button.addEventListener("click", generateRandomNumber, minValue, maxValue);
<div class="outer-box">
<div class="generator-box">
<h1> Random Number Generator </h1>
<div class="inputs">
<label for="min">Min Value:</label>
<input type="number" id="min" name="min" placeholder="Enter min value"><br><br>
<label for="max">Max Value:</label>
<input type="number" id="max" name="max" placeholder="Enter max value"><br><br>
</div>
<span class=random-number>Click to generate</span>
<hr>
<div class="buttons">
<button class='button1'>Generate</button>
</div>
</div>
</div>
Thank you
Only create variables that references the elements, ex. minInput, maxInput,
add event listeners to the elements. 'click' for the button and 'change' for the inputs,
use parseInt and store the input values in variables,
check if any of them is NaN (not a number),
generate a number of both inputs have numbers.
If I were you, I would give both the button and the .random-number span unique ids too, in order to hint that they are referenced in javascript code.
const numberGenerator = document.querySelector(".random-number");
const generateButton = document.querySelector(".button1");
const minInput = document.getElementById("min"); // 1
const maxInput = document.getElementById("max"); // 1
generateButton.addEventListener('click', generateRandomNumber); // 2
minInput.addEventListener('change', generateRandomNumber); // 2
maxInput.addEventListener('change', generateRandomNumber); // 2
function generateRandomNumber() {
let min = parseInt(minInput.value); // 3
let max = parseInt(maxInput.value); // 3
const BOTH_INPUTS_GOT_VALUES = !isNaN(min) && !isNaN(max); // 4
if (BOTH_INPUTS_GOT_VALUES) { // 5
randomNumber = Math.floor(Math.random() * (max - min)) + min;
numberGenerator.innerHTML = randomNumber;
}
}
.inputs {
margin-bottom: 1rem;
}
<div class="outer-box">
<div class="generator-box">
<h1> Random Number Generator </h1>
<div class="inputs">
<label for="min">Min Value:</label>
<input type="number" id="min" name="min" placeholder="Enter min value">
<label for="max">Max Value:</label>
<input type="number" id="max" name="max" placeholder="Enter max value">
</div>
<span class=random-number>Click to generate</span>
<hr>
<div class="buttons">
<button class='button1'>Generate</button>
</div>
</div>
</div>
To Get The Updated Value You Have To Put
const minValue = document.querySelector("#min").value;
const maxValue = document.querySelector("#max").value;
Inside
let generateRandomNumber = () => {...}
If You Put It Outside of generateRandomNumber then it will set the values of inputs when the page is loaded And If You Put It In The generateRandomNumber then It will reassign when that function is called
const numberGenerator = document.querySelector(".random-number");
const button = document.querySelector(".button1");
let generateRandomNumber = () => {
var min = document.querySelector("#min").value;
var max = document.querySelector("#max").value;
min = Math.ceil(min);
max = Math.floor(max);
randomNumber = Math.floor(Math.random() * (max - min + 1)) + min;
numberGenerator.innerHTML = randomNumber;
};
button.addEventListener("click", generateRandomNumber);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Random Number Generator</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="outer-box">
<div class="generator-box">
<h1> Random Number Generator </h1>
<div class="inputs">
<label for="min">Min Value:</label>
<input type="number" id="min" name="min" placeholder="Enter min value"><br><br>
<label for="max">Max Value:</label>
<input type="number" id="max" name="max" placeholder="Enter max value"><br><br>
</div>
<span class=random-number>Click to generate</span>
<hr>
<div class="buttons">
<button class='button1'>Generate</button>
</div>
</div>
</div>
<script src='random_number_generator.js'></script>
</body>
</html>
Update : Get The Updated Value On Input ( Before Pressing The Button )
const numberGenerator = document.querySelector(".random-number");
const button = document.querySelector(".button1");
const error = document.querySelector(".error");
const minInput = document.getElementById("min");
const maxInput = document.getElementById("max");
var min = 0;
var max = 0;
maxInput.oninput = valueDetected;
minInput.oninput = valueDetected;
function valueDetected(){
console.log("Max: "+maxInput.value+" & Min: "+minInput.value)
}
let generateRandomNumber = () => {
min = Math.ceil(min);
max = Math.floor(max);
randomNumber = Math.floor(Math.random() * (max - min + 1)) + min;
numberGenerator.innerHTML = randomNumber;
};
button.addEventListener("click", generateRandomNumber);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Random Number Generator</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="outer-box">
<div class="generator-box">
<h1> Random Number Generator </h1>
<div class="inputs">
<label for="min">Min Value:</label>
<input type="number" id="min" name="min" placeholder="Enter min value" value=0><br><br>
<label for="max">Max Value:</label>
<input type="number" id="max" name="max" placeholder="Enter max value" value=0><br><br>
</div>
<span class=random-number>Click to generate</span>
<hr>
<div class="buttons">
<button class='button1'>Generate</button>
</div>
</div>
<script src='random_number_generator.js'></script>
</body>
</html>
Validated One
const numberGenerator = document.querySelector(".random-number");
const button = document.querySelector(".button1");
const error = document.querySelector(".error");
const minInput = document.getElementById("min");
const maxInput = document.getElementById("max");
var min = 0;
var max = 0;
maxInput.oninput = checkValid;
minInput.oninput = checkValid;
function checkValid(){
if(parseInt(maxInput.value) < parseInt(minInput.value)){
button.style.display = "none";
error.style.display = "block";
}
else {
button.style.display = "block";
error.style.display = "none";
min = minInput.value;
max = maxInput.value;
}
}
let generateRandomNumber = () => {
min = Math.ceil(min);
max = Math.floor(max);
randomNumber = Math.floor(Math.random() * (max - min + 1)) + min;
numberGenerator.innerHTML = randomNumber;
};
button.addEventListener("click", generateRandomNumber);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Random Number Generator</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="outer-box">
<div class="generator-box">
<h1> Random Number Generator </h1>
<div class="inputs">
<label for="min">Min Value:</label>
<input type="number" id="min" name="min" placeholder="Enter min value" value=0><br><br>
<label for="max">Max Value:</label>
<input type="number" id="max" name="max" placeholder="Enter max value" value=0><br><br>
</div>
<span class=random-number>Click to generate</span>
<hr>
<div class="buttons">
<button class='button1'>Generate</button>
<span class="error" style="color: red; display: none;">You Cannot Put A Maximum Value Less Than The Minimum Value</span>
</div>
</div>
</div>
<script src='random_number_generator.js'></script>
</body>
</html>
You need to add onclick event in button and call funcation.
And if you want before clicking the button then you need to add min and max textbox onchange event and write your logic
please check following way
<button class='button1' onclick="generateRandomNumber()">Generate</button>
And this your logic in funcation.
<script>
function generateRandomNumber() {
const numberGenerator = document.querySelector(".random-number");
const button = document.querySelector(".button1");
const minValue = document.querySelector("#min").value;
const maxValue = document.querySelector("#max").value;
randomNumber = Math.floor(Math.random() * (maxValue-minValue)) + minValue
numberGenerator.innerHTML = randomNumber;
}
</script>
I've got a very simple form and I'm want the values to empty when I submit in order to use again without refreshing the page. What I've got isn't working for some reason.
My initial idea was to set the values of the inputs to empty strings on form submit, but when I log them into the console they don't do that. Anyone know what I'm doing wrong here?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<form id="form">
<input id="volume" type="text" />
<input id="denied" type="text" />
<input id="charges" type="number" step="any" />
<button id="submit" type="btn-submit">Submit</button>
</form>
<div class="results">
<p class="rate">Current Denial Rate: </p>
<p class="recoverable">Recoverable Dollars: </p>
</div>
<script src="script.js"></script>
</body>
</html>
let form = document.getElementById("form");
let volume = document.getElementById("volume");
let denied = document.getElementById("denied");
let charges = document.getElementById("charges");
let submit = document.getElementById("btn-submit");
let results = document.querySelector(".results");
let rate = document.querySelector(".rate");
let recoverable = document.querySelector(".recoverable");
form.onsubmit = function (e) {
e.preventDefault();
volume = volume.value;
denied = denied.value;
charges = charges.value;
let curDenialRate = parseFloat((denied / volume) * 100);
charges = parseFloat(charges * 0.4);
function formatNumber(num) {
let formattedNum = num.toFixed(2);
return formattedNum;
}
let recoverableDollars = "$" + formatNumber(charges);
curDenialRate = formatNumber(curDenialRate) + "%";
rate.append(curDenialRate);
recoverable.append(recoverableDollars);
volume = " ";
denied = " ";
charges = " ";
return false;
};
Use HTMLFormElement.reset():
let form = document.getElementById("form");
const volume = document.getElementById("volume");
const denied = document.getElementById("denied");
const charges = document.getElementById("charges");
let submit = document.getElementById("btn-submit");
let results = document.querySelector(".results");
let rate = document.querySelector(".rate");
let recoverable = document.querySelector(".recoverable");
form.onsubmit = function(e) {
e.preventDefault();
let a = volume.value;
let b = denied.value;
let c = charges.value;
let curDenialRate = parseFloat((b / a) * 100);
c = parseFloat(c * 0.4);
function formatNumber(num) {
let formattedNum = num.toFixed(2);
return formattedNum;
}
let recoverableDollars = "$" + formatNumber(c);
curDenialRate = formatNumber(curDenialRate) + "%";
rate.append(curDenialRate);
recoverable.append(recoverableDollars);
form.reset();
return false;
};
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<form id="form">
<input id="volume" type="text" />
<input id="denied" type="text" />
<input id="charges" type="number" step="any" />
<button id="submit" type="btn-submit">Submit</button>
</form>
<div class="results">
<p class="rate">Current Denial Rate: </p>
<p class="recoverable">Recoverable Dollars: </p>
</div>
<script src="script.js"></script>
</body>
</html>
How you are clearing values will not work. You are trying to change the variable but that will not affect the DOM element or its value.
You will have to use the below code with value property to change the value.
document.getElementById("volume").value= " ";
document.getElementById("denied").value= " ";
document.getElementById("charges").value= " ";
Im trying to get this program to work and i have everything running, but my values return as NaN. I've tried initializing the variables as numbers both in and outside the function to no avail. Any help?
EDIT: added in the entire script, html and all incase it helps alongside the edits suggested thus far.
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<title>Placeholder</title>
</head>
<body>
<header>
<h1>Resturant Calculator</h1>
</header>
<article>
<fieldset>
<label for="bill">
Bill Amount
</label>
<input type="number" id="bill" />
</fieldset>
<fieldset>
<label for="tip">
Tip Percent
</label>
<input type="number" id="tip" />
<label>(enter as whole number)</label>
</fieldset>
<fieldset>
<label for="peeps">
# of people
</label>
<input type="number" id="peeps" />
</fieldset>
<button id="submit" onclcick="calculate()">Calculate</button>
<p id="tipAmount">Tip Amount:</p>
<p id="total">Total Bill:</p>
<p id="totalByPeep">Total per Person:</p>
</article>
<script>
"use strict"
var bill = document.getElementById("bill").value;
var tip = document.getElementById("tip").value;
var peeps = document.getElementById("peeps").value;
var total;
var totalTip;
var tpPerson;
function calculate(){
totalTip = bill.value / (tip.value * 0.01);
total = bill.value + totalTip;
tpPerson = total / peeps.value;
document.getElementById("tipAmount").innerHTML = "Tip Amount: " + totalTip;
document.getElementById("total").innerHTML = "Total: " + total;
document.getElementById("totalByPeep").innerHTML = "Total per Person: " + tpPerson;
}
function createEventListener(){
var submitButton = document.getElementById("submit");
if (submitButton.addEventListener){
submitButton.addEventListener("click", calculate, false);
}
else if(submitButton.attachEvent){
submitButton.attachEvent("onclick", calculate);
}
}
if (window.addEventListener){
window.addEventListener("load", createEventListener, false);
}
else if (window.attachEvent){
window.attachEvent("onload", createEventListener);
}
</script>
</script>
</body>
</html>
You need to get the values from the elements bill,tip,peeps
Probably something like document.getElementById("bill").value
Using just document.getElementById("bill") you are selecting the element, but not its value
You need to read the value inside calculate()
function calculate(){
bill = +bill.value, tip = +tip.value, peeps = +peeps.value;
totalTip = bill/ (tip * 0.01);
total = bill + totalTip;
tpPerson = total / peeps;
document.getElementById("tipAmount").innerHTML = "Tip Amount: " + totalTip;
document.getElementById("total").innerHTML = "Total: " + total;
document.getElementById("totalByPeep").innerHTML = "Total per Person: " + +tpPerson;
}