How to get a span element to show a value? - javascript

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;
}

Related

Create a JavaScript program that will compute for the Volume of a cuboid. Show the volume with complete description

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>

Getting updated value from Input text using Vanilla 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>

Program returning values as NaN

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;
}

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>

Date function isn't working as expected

I'm trying to insert the current year into a copyright statement and it's not working - likely because of something really basic. Any help? Thanks. :)
ps If there are any other stylistic issues, I welcome all comments.
$(document).ready(function ()
{
// Veterinary Calculator Code
// define variables for body weight, dehydration and ongoing losses
$bw = $('#bodyWeight');
$dh = $('#dehydration');
$ol = $('#ongoingLosses');
// update maint, replacement, dailyRequirement and rate when bw, dh or ol changes.
function updateDetails()
{
var $dr = $('#dailyRequirement');
var $repl = $('#replacement');
var $rt = $('#rate');
var ol = parseInt($ol.val());
var mt = parseInt(1.5 * (70 * (Math.pow($bw.val(), 0.75)))); // maintenance requirement
$dr.text(mt + ' ml/24 hours');
var rep = parseInt($bw.val() * 10 * $dh.val()); // replacement amount
$repl.text(rep + ' ml');
var rt = parseInt((mt + rep + ol) / 24); // total fluid rate
$rt.text(rt + ' ml/hr');
}
// add event listeners for input elements
$bw.on('change', updateDetails);
$dh.on('change', updateDetails);
$ol.on('change', updateDetails);
// Insert current year into copyright statement
var dateNow = new Date();
var thisYear = dateNow.getFullYear();
var elYear = $('#currentYear');
elYear.text = thisYear;
});
<body>
<div>
<header>
<h1>Fluid Calculator</h1>
</header>
<div>
<fieldset id="params">
<legend>Inputs</legend>
<label>Body Weight (kg):</label><br />
<input type="number" id="bodyWeight" autofocus min="0" />
<br><br />
<label>% Dehydration:</label><br />
<input type="number" id="dehydration"/>
<br /><br />
<label>Ongoing Losses (ml):</label><br />
<input type="number" id="ongoingLosses" />
<br /><br />
</fieldset><br />
<label>Daily Requirement:</label> <label class="result" id="dailyRequirement">0 ml</label> <br />
<label>Replacement:</label> <label class="result" id="replacement">0 ml</label> <br />
<br />
<label> Rate (ml/hr):</label> <label class="result" id="rate">0 ml/hr</label>
</div>
<footer>
<p>
© Copyright 2014-<span id="currentYear">year</span> by VETsharp Pty Ltd
</p>
</footer>
</div>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<script type="text/javascript" src="vc.js"></script>
</body>
$("#currentYear").text(thisYear);
In order to replace the text of the currentYear <span>, you need to use:
$('#currentYear').replaceWith(thisYear);

Categories