Getting updated value from Input text using Vanilla JavaScript - javascript

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>

Related

How to calculate the grade the person received

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;

How to get a span element to show a value?

I have an HTML file with a .js file that has the javascript.
In the HTML file I have <p>Total Estimate: <span id= "estimate"></span></p>
But nothing shows up when opened in a browser. This is a practice that you are supposed to go along with in my textbook and as far as I can see, I am doing it correctly. I am getting an error in the JS that says
ERROR:'document' is not defined.[no-undef]
This is where ever document is seen in the JS.
This is my JS code. Is there a problem I don't see?
// global variables
var photographerCost = 0;
var totalCost = 0;
var memoryBook = false;
var reproductionRights = false;
// calculates all costs based on staff and adds to total cost
function calcStaff() {
var num = document.getElementById("photognum");
var hrs = document.getElementById("photoghrs");
var distance = document.getElementById("distance");
totalCost -= photographerCost;
photographerCost = num.value * 100 * hrs.value + distance.value * num.value;
totalCost += photographerCost;
document.getElementById("estimate") .innerHTML = "$" + totalCost;
}
// adds/subtracts cost of memory book from total cost
function toggleMembook() {
(document.getElementById("membook") .checked === false) ?
totalCost -= 250 : totalCost + 250;
document.getElementById("estimate") .innerHTML = "$" + totalCost;
}
// ads/subtracts cost of reproduction rights from total cost
function toggleRights() {
(document.getElementById('reprodrights') .checked === false) ?
totalCost -= 1250 : totalCost += 1250;
document.getElementById("estimate") .innerHTML = "$" + totalCost;
}
// sets all form field values to defaults
function resetForm() {
document.getElementById ("photognum") .value = 1;
document.getElementById ("photoghrs") .value =2;
document.getElementById ("membook") .checked = memoryBook;
document.getElementById ("reprodrights") .checked = reproductionRights;
document.getElementById ("distance") .value = 0;
calcStaff();
createEventListeners();
}
// creates event listeners
function createEventListeners() {
document.getElementById("photognum") .addEventListener("change", calcStaff, false);
document.getElementById("photoghrs") .addEventListener("change", calcStaff, false);
document.getElementById("membook") .addEventListener("change", toggleMembook, false);
document.getElementById("reprodrights") .addEventListener("change", toggleRights, false);
document.getElementById("distance") .addEventListener("change", calcStaff, false);
}
// resets form when page is reloaded
document.addEventListener("load", resetForm, false);
Below is HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>Fan Trick Fine Art Photography - Estimate</title>
<link rel="stylesheet" media="screen and (max-device-width: 999px)" href="fthand.css" />
<link rel="stylesheet" media="screen and (min-device-width: 1000px)" href="fantrick.css" />
<!--[if lt IE 9]>
<link rel="stylesheet" href="ftie.css" />
<![endif]-->
<link href='http://fonts.googleapis.com/css?family=Mr+Bedfort' rel='stylesheet' type='text/css'>
<script src="modernizr.custom.05819.js"></script>
</head>
<body>
<div id="container">
<header>
<h1>
<img src="images/ftlogo.png" alt="Fan Trick Fine Art Photography" title="" />
</h1>
</header>
<nav>
<ul>
<li>About</li>
<li>Portfolio</li>
<li id="currentpage">estimate</li>
<li>Digital 101</li>
</ul>
</nav>
<article>
<h2>Estimate</h2>
<p>Our experienced, professional photography team is available to capture memories of your wedding, celebration, or other special event.</p>
<p>Choose the custom options that fit your needs:</p>
<form id="estimateform">
<fieldset>
<legend><span>Photography</span></legend>
<input type="number" min="0" max="4" id="photognum" value="1" />
<label for="photognum">
<p># of photographers (1‑4)</p>
<p>$100/hr</p>
</label>
<input type="number" min="2" id="photoghrs" value="2" />
<label for="photoghrs">
<p># of hours to photograph (minimum 2)</p>
</label>
<input type="checkbox" id="membook" />
<label for="membook">
<p>Memory book</p>
<p>$250</p>
</label>
<input type="checkbox" id="reprodrights" />
<label for="reprodrights">
<p>Reproduction rights for all photos</p>
<p>$1250</p>
</label>
</fieldset>
<fieldset>
<legend><span>Travel</span></legend>
<input type="number" id="distance" value="0" />
<label for="distance">
<p>Event distance from Austin, TX</p>
<p>$1/mi per photographer</p>
</label>
</fieldset>
</form>
</article>
<aside>
<p>Total Estimate: <span id= "estimate"></span></p>
</aside>
<footer>
<p>Fan Trick Fine Art Photography • Austin, Texas</p>
</footer>
</div>
<script src="ft.js"></script>
</body>
</html>
You can try this code below
function calcStaff() {
var num = document.getElementById("photognum");
var hrs = document.getElementById("photoghrs");
var distance = document.getElementById("distance");
totalCost -= photographerCost;
//You need use Number to change all value
//fix
photographerCost = Number(num.value) * 100 * Number(hrs.value) + Number(distance.value) * Number(num.value);
//============//
//This code systax not support
//photographerCost = num.value * 100 * hrs.value + distance.value * num.value;
totalCost += photographerCost;
document.getElementById("estimate") .innerHTML = "$" + totalCost;
}

JS and onchange event in html form

My code error is pretty obvious but I can´t see it.
It's very simple my form ask the height and weight and calculate the corporal mass index the user input height in meters and convert to inches (function works ok)
input kilos and convert to pounds (works ok too) but in this process must calculate the index and write it in another textbox. that's my problem!
What am I doing wrong??? heres my code:
function myFunctionmts() {
var x = document.getElementById("mters");
var y = document.getElementById("inches");
y.value = ((x.value*100)/2.54).toFixed(2);
document.getElementById("mters").value=x.value;
document.getElementById("inches").value=y.value;
}
</script>
<script>
function myFunctionkg() {
var i = document.getElementById("imc");
var p = document.getElementById("inches");
var x = document.getElementById("kilos");
var z = document.getElementById("pounds");
var step1 = 0;
var step2 = 0;
var step3 = 0;
z.value = (x.value/.454).toFixed(2);
libras.value=z.value;
document.getElementById("pounds").value=z.value;
step1.value = z.value*703;
step2.value = step1.value/p.value;
step3.value = (step2.value/p.value).toFixed(1);
document.getElementById("imc").value=step3.value
}
<form method="POST" action="#">
<input type="text" name="mters" id="mters" required onchange="myFunctionmts()">
<input type="text" name="inches" id="inches" placeholder="Inches" readonly>
<input type="text" name="kilos" id="kilos" required onchange="myFunctionkg()">
<input type="text" name="pounds" id="pounds" placeholder="Pounds" readonly>
<input type="text" name="imc" id="imc" readonly>
<input type="submit" value="Save">
</form>
Try to use this code:
HTML :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Stack Overflow</title>
<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
/>
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<form method="POST" action="#">
<label for="mters">meter</label>
<input
type="text"
name="mters"
id="mters"
required
onchange="myFunctionmts()"
/>
<label for="inches">inches</label>
<input
type="text"
name="inches"
id="inches"
placeholder="Inches"
readonly
/>
<label for="kilos">kilos</label>
<input
type="text"
name="kilos"
id="kilos"
required
onchange="myFunctionkg()"
/>
<label for="pounds">pounds</label>
<input
type="text"
name="pounds"
id="pounds"
placeholder="Pounds"
readonly
/>
<label for="imc">imc</label>
<input type="text" name="imc" id="imc" readonly />
<input type="submit" value="Save" />
</form>
<script src="script.js"></script>
</body>
</html>
JS:
function myFunctionmts() {
var x = document.getElementById('mters');
var y = document.getElementById('inches');
y.value = ((x.value * 100) / 2.54).toFixed(2);
document.getElementById('mters').value = x.value;
document.getElementById('inches').value = y.value;
}
function myFunctionkg() {
var imc = document.getElementById('imc'); // mass index
var inches = document.getElementById('inches'); //
var kilos = document.getElementById('kilos');
var pounds = document.getElementById('pounds'); // pounds
var step1 = 0;
var step2 = 0;
var step3 = 0;
pounds.value = (+kilos.value / 0.454).toFixed(2);
// undefined error here, what is this libras all about ???
// libras.value = z.value;
step1 = +pounds.value * 703;
step2 = +step1 / +inches.value;
step3 = (+step2 / +inches.value).toFixed(1);
console.log(step3);
imc.value = step3;
}
Hope it helps.

HTML output not updating/calculating after 1st button click

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>
`

When I click the Calculate button, it does not display the calculations in textbox for sales tax and total

When I run the code on my chrome browser, clicking the calculate button, it does not put the value in the Total and Sales Tax text box.
Also "Add the Javascript event handler for the click event of the Clear button, This should clear all text boxes and move the cursor to the Subtotal field."
I'm using Html and js file. Using a function expression to calculate and display my calculation, then also use the clear button to clear all text boxes.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Sales Tax Calculator</title>
<link rel="stylesheet" href="styles.css" />
<script src="sales_tax.js"></script>
</head>
<body>
<main>
<h1>Sales Tax Calculator</h1>
<p>Enter Subtotal and Tax Rate and click "Calculate".</p>
<label for="subtotal">Subtotal:</label>
<input type="text" id="subtotal" ><br>
<label for="tax_rate">Tax Rate:</label>
<input type="text" id="tax_rate" ><br>
<label for="sales_tax">Sales Tax:</label>
<input type="text" id="sales_tax" disabled ><br>
<label for="total">Total:</label>
<input type="text" id="total" disabled ><br>
<label> </label>
<input type="button" id="calculate" value="Calculate" >
<input type="button" id="clear" value="Clear" ><br>
</main>
</body>
</html>
This is my js file.
var $ = function (id) {
return document.getElementById(id);
};
var SumSalesTax = function (sub, rate){
var sales_tax = (sub * rate);
sales_tax = sales_tax.toFixed(2);
var total = (sub * rate + sub);
total = total.toFixed(2);
return sales_tax, total;
}
var processEntries = function() {
var sub = parseFloat($("subtotal").value);
var rate = parseFloat($("tax_rate").value);
if (sub < 0 && sub > 10000 && rate < 0 && rate > 12) {
alert("Subtotal must be > 0 and < 1000, and Tax Rate must be >0 and < 12.
")
} else {
$("sales_tax").value = SumSalesTax(sub, rate);
$("total").value = SumSalesTax(sub, rate);
}
};
window.onload = function() {
$("calculate").onclick = processEntries;
$("clear").onclick = sumSalesTax;
};
Sales Tax Calculator
It seems like you had a typo when you were doing $("clear").onclick = sumSalesTax;, as the variable was named SumSalesTax rather than with the lower case. This meant that the code block errored out and therefore didn't actually run. Make sure you make good use of the browser console so you can spot errors like this! The below example should work
var $ = function (id) {
return document.getElementById(id);
};
var SumSalesTax = function (sub, rate){
var sales_tax = (sub * rate);
sales_tax = sales_tax.toFixed(2);
var total = (sub * rate + sub);
total = total.toFixed(2);
return sales_tax, total;
}
var processEntries = function() {
var sub = parseFloat($("subtotal").value);
var rate = parseFloat($("tax_rate").value);
if (sub < 0 && sub > 10000 && rate < 0 && rate > 12) {
alert("Subtotal must be > 0 and < 1000, and Tax Rate must be >0 and < 12.")
} else {
$("sales_tax").value = SumSalesTax(sub, rate);
$("total").value = SumSalesTax(sub, rate);
}
};
window.onload = function() {
$("calculate").onclick = processEntries;
$("clear").onclick = SumSalesTax;
};
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Sales Tax Calculator</title>
<link rel="stylesheet" href="styles.css" />
<script src="sales_tax.js"></script>
</head>
<body>
<main>
<h1>Sales Tax Calculator</h1>
<p>Enter Subtotal and Tax Rate and click "Calculate".</p>
<label for="subtotal">Subtotal:</label>
<input type="text" id="subtotal" ><br>
<label for="tax_rate">Tax Rate:</label>
<input type="text" id="tax_rate" ><br>
<label for="sales_tax">Sales Tax:</label>
<input type="text" id="sales_tax" disabled ><br>
<label for="total">Total:</label>
<input type="text" id="total" disabled ><br>
<label> </label>
<input type="button" id="calculate" value="Calculate" >
<input type="button" id="clear" value="Clear" ><br>
</main>
</body>
</html>

Categories