Date function isn't working as expected - javascript

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

Related

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

Trying to calculate a simple discount and sales tax in javascript

I'm just trying to input an number and then add 10% and then take that total and .08% tax. Can you please help me figure out what I'm doing wrong. I sure it is something simple I'm overlooking but I'm new to this and can't figure what is wrong.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Price tool</title>
</head>
<body>
<form name="operation_form">
<label style="font-size:20px"><b>Price Tool</b></label>
<br/>
<br/>
<br/>
<label>Item Price: </label><input type="number" name='acertscore' value="" />
<br/>
<br/>
<label><b>Total is:</b></label><input type="number" name="answerbox">
<br/>
<input type="button" value="Calculate" onclick="costCalc();" />
<br/>
<input type="button" value="Reset" onClick="this.form.reset()" />
</form>
<script type="text/javascript">
function costCalc() {
var form = document.forms["operation_form"];
var x = form["acertscore"].value;
var cost = (x * .1) + x;
var answer = (cost * .08) + cost;
form["answerbox"].value = answer;
}
</script>
</body>
</html>
I logged the value of 'cost' in your code when I start with the value 100
var cost = (x * .1) + x;
console.log(cost);
and got a value of '10100'
But if I make sure that x is a number I get the correct value (110)
var cost = (x * .1) + Number(x);
console.log(cost);
And I get 118.8 for the total.
When you retrieve the value from your input control, it comes through as a string value.
var x = form["acertscore"].value; // x is a string
If you convert this to a number immediately you'll avoid additional problems.
var x = Number(form["acertscore"].value); // x is a number
function costCalc() {
var form = document.forms["operation_form"];
var x = Number(form["acertscore"].value);
var cost = (x * .1) + x;
var answer = (cost * .08) + cost;
form["answerbox"].value = answer;
}
<form name="operation_form">
<label style="font-size:20px"><b>Price Tool</b></label>
<br/>
<br/>
<br/>
<label>Item Price: </label><input type="number" name="acertscore" value="" />
<br/>
<br/>
<label><b>Total is:</b></label><input type="number" name="answerbox">
<br/>
<input type="button" value="Calculate" onclick="costCalc();" />
<br/>
<input type="button" value="Reset" onClick="this.form.reset()" />
</form>
The problem is that your answer number is so long that it tries to display exponents. Because of this, the number gets treated as a string, though you've specified that the output goes into an <input> field with a type of number. Because your answer is not a number, it can't be displayed.
To resolve this, you can parse the output as a float before displaying it:
form["answerbox"].value = parseFloat(answer);
function costCalc() {
var form = document.forms["operation_form"];
var x = form["acertscore"].value;
var cost = (x * .1) + x;
var answer = (cost * .08) + cost;
form["answerbox"].value = parseFloat(answer);
}
<form name="operation_form">
<label style="font-size:20px"><b>Price Tool</b></label>
<br/>
<br/>
<br/>
<label>Item Price: </label><input type="number" name='acertscore' value="" />
<br/>
<br/>
<label><b>Total is:</b></label><input type="number" name="answerbox">
<br/>
<input type="button" value="Calculate" onclick="costCalc();" />
<br/>
<input type="button" value="Reset" onClick="this.form.reset()" />
</form>
Hope this helps!

Loan Calculator (jQuery) not working right

I have a loan calculator that I have built using JQuery, HTML, and CSS. It functions ok. The weird thing is I have to refresh the page in order to get it to calculate correctly. I'm not sure what I'm doing (or not doing) correctly. Would love some feedback.
$(document).ready(function() {
// variables
var amount = $('#loanAmount').val();
var yearlyInterestRate = .12;
var monthlyInterestRate = yearlyInterestRate / 12;
var twelveMon = 12;
var eighteenMon = 18;
var twentyFourMon = 24;
var duration = $('input[name=duration]:checked').val();
var calcButton = $('.calculate');
var resetButton = $('.reset');
var monthPay;
$('.results').addClass('hidden');
// Calculate Monthly Payment
calcButton.click(function(event) {
event.preventDefault();
monthPay = (monthlyInterestRate * amount) / [1 - Math.pow((1 + monthlyInterestRate), -duration)];
$('.durationValue').text(duration);
$('.monthlyPayment').text(Math.round(monthPay));
$('.results').removeClass('hidden');
});
resetButton.click(function() {
$(form).reset();
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<section id="loan-calc">
<form id="calculator">
<input type="text" name="loanAmount" id="loanAmount" placeholder="Loan Amount"><br>
<label>Choose your payment duration:</label><br>
<input type="radio" name="duration" value="12" class="duration"> 12 Months<br>
<input type="radio" name="duration" value="18" class="duration"> 18 Months<br>
<input type="radio" name="duration" value="24" class="duration"> 24 Months <br>
<button class="calculate">Calculate</button>
<!-- <button class="rest">Reset</button>-->
</form>
<p class="results">You chose a duration of <span class="durationValue"></span> months and your monthly payment is $<span class="monthlyPayment"></span> at a 12% yearly interest rate.</p>
</section>
You're setting values on document.ready() - so it's even before any of examples in radio will be clicked. Move getting you values into the .click() function
And it's even more efficient to switch from deprecated .click() method to .on('click', function(){}) just in case you'll expand your form in the future
You need to put the vars inside the function that uses them
PS: In a form an input type="reset" /> will reset the form without needing script
$(document).ready(function() {
$('.results').addClass('hidden');
var yearlyInterestRate = .12;
var monthlyInterestRate = yearlyInterestRate / 12;
var twelveMon = 12;
var eighteenMon = 18;
var twentyFourMon = 24;
// Calculate Monthly Payment
$('.calculate').on("click", function(event) {
event.preventDefault();
var amount = $('#loanAmount').val();
var duration = $('input[name=duration]:checked').val();
var monthPay = (monthlyInterestRate * amount) / [1 - Math.pow((1 + monthlyInterestRate), -duration)];
$('.durationValue').text(duration);
$('.monthlyPayment').text(Math.round(monthPay));
$('.results').removeClass('hidden');
});
$('.reset').on("click", function() {
$(form).reset();
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<section id="loan-calc">
<form id="calculator">
<input type="text" name="loanAmount" id="loanAmount" placeholder="Loan Amount"><br>
<label>Choose your payment duration:</label><br>
<input type="radio" name="duration" value="12" class="duration"> 12 Months<br>
<input type="radio" name="duration" value="18" class="duration"> 18 Months<br>
<input type="radio" name="duration" value="24" class="duration"> 24 Months <br>
<button class="calculate">Calculate</button>
<!-- <button class="rest">Reset</button>-->
</form>
<p class="results">You chose a duration of <span class="durationValue"></span> months and your monthly payment is $<span class="monthlyPayment"></span> at a 12% yearly interest rate.</p>
</section>
you take the values of duration and amount on pageload (document ready). if you update the values by filling them in, the variables won't get updated.
move var amount = $('#loanAmount').val(); and var duration = $('input[name=duration]:checked').val(); into the 'onClick' handler so that the amount and duration get updated once you click.

Jquery BMI equation not working in form tag

Been stuck on this for a few hours, running out of ideas. I have two BMI equations (metric, standard), both working correctly. I have them set up in Jquery UI tabs with a form. The first equation (metric) works perfectly. I can't seem to get the second equation to work. It works when it's standalone, but not when I insert it with the first equation. Should I have not created a new script tag for the second equation?
<html>
<head>
<link rel="stylesheet" href="../jquery-ui/jquery-ui.min.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="../jquery-mousewheel-master/jquery.mousewheel.min.js"></script>
<script>
$(function() {
// get user input
var input = function() {
var height = $("#height").val();
var weight = $("#weight").val();
var calculated_bmi = BMI(height, weight);
$('#result').text(calculated_bmi);
}
var BMI = function(h, w) {
// convert into centimeters
var h = h / 100;
var h_squared = h * h;
var result = w / h_squared;
return result.toFixed(1);
}
$("#calculate").click(function() {
input();
})
$(function() {
$("#tabs").tabs();
});
$("#weight").spinner();
$("#height").spinner();
});
</script>
<script>
"use strict";
$(function() {
$("#bmicalc").submit(function(e) {
e.preventDefault();
var heightFt = $("#height_ft").val();
heightIn = $("#height_in").val();
height = parseFloat(heightFt * 12) + parseFloat(heightIn);
weight = $("#weight1").val();
BMI = calculateBMI(height, weight);
$("#result2").text('Your BMI is ' + BMI);
});
function calculateBMI(height, weight) {
var BMI = (weight / (height * height)) * 703
return Math.round(BMI * Math.pow(10, 2)) / Math.pow(10, 2);
}
$("#weight").spinner();
$("#height").spinner();
$("#height_ft").spinner();
$("#height_in").spinner();
$("#weight1").spinner();
});
</script>
</head>
<body>
<div class="wrapper">
<h2 class="subtitle">Enter your information</h2>
<form id="bmicalc">
<div id="tabs">
<ul>
<li>Metric</li>
<li>Standard</li>
</ul>
<div id="tabs-1">
<div>
<div>
Height (centimeters): <input type="spinner" id="height" min="1" max="300"> Weight (kilograms): <input type="spinner" id="weight" min="1" max="450">
</div>
<input type="button" id="calculate" value="Calculate">
<p class="resultwords">Your BMI is: <span id="result"></span></p>
</div>
</div>
<div id="tabs-2">
<div id="calc-id2">
<p>
<label>Height:
<input type="text" id="height_ft" min="1" max="10">feet
<input type="text" id="height_in" min="1" max="11">inches</label>
</p>
<p>
<label>Weight:
<input type="text" id="weight1" min="1" max="1000">pounds</label>
</p>
<input type="submit" id="bmicalc1" value="Calculate">
<p class="resultwords">Your BMI is: <span id="result2"></span></p>
</div>
</div>
</div>
</form>
</div>
</body>
</html>

Change value of input box based on selected item and other value

So basically, I am creating an application form for gym membership.
The base cost is $100. If juggling is selected, the cost will increase by $50.
Also, the base cost will increase by $50 if the 'BMI' is > 25 and <= 30. If the 'BMI' is > 30, it will increase by $100 instead.
This is my code. It is not working as intended. Would like some help. Thanks a lot.
<!DOCTYPE html>
<html>
<head>
<title>UWS application form</title>
<link rel="stylesheet" href="Prac1Task2.css" />
</head>
<body>
<form>
<fieldset>
<legend>Fitness Details</legend>
Favourite Activities: <br/>
<input type="checkbox" name="activity" value="cycling" id="cycling"><label for="cycling">Cycling</label>
<input type="checkbox" name="activity" value="50" id="juggling" onchange="update(this);"><label for="juggling">Juggling</label>
<br/>
<br/>
<label for="height">What is your height (Meters)</label><br/>
<input type="number" name="height" id="height" class="input" onchange="getBMI()">
<br/>
<label for="weight">What is your weight? (kg)</label><br/>
<input type="number" name="weight" id="weight" class="input" onchange="getBMI()">
<br/>
<label for="bmi">BMI:</label><br/>
<input type="number" name="bmi" id="bmi" class="input" value="" readonly>
<script>
function getBMI()
{
var height = document.getElementById("height").value;
var weight = document.getElementById("weight").value;
document.getElementById("bmi").value = (weight / height) / height;
var bmi = document.getElementById("bmi");
var price = document.getElementById("price").value;
if (bmi.value > 25 && bmi.value <= 30)
{
parseInt(price.value) += parseInt(50);
document.getElementById('price').value = price.value;
}
else if (bmi.value > 30)
{
document.getElementById("price").value = document.getElementById("price").value + 100;
}
}
</script>
</fieldset>
<br/>
<fieldset>
<legend>Application Details</legend>
Date of Application:<br/>
<input class="input" id="date" name="date" readonly />
<script>
var timetime = new Date();
document.getElementById("date").value = (timetime.getDate() + "/" + (timetime.getMonth() + 1)
+ "/" + timetime.getFullYear());
</script>
<br/><br/>
Cost of Application: <br/>
$<input type="number" class="input" id="price" name="price" step="0.01" value="100" readonly />
<script>
var total = 100;
function update(feature) {
if(feature.checked == true){
total += parseInt(feature.value);
document.getElementById('price').value = total;
}
if(feature.checked == false){
total -= parseInt(feature.value);
document.getElementById('price').value = total;
}
}
</script>
</fieldset>
<br/>
<input type="submit" value="Submit" class="button">
</form>
</body>
</html>
You haven't mentioned the exact issue which you are facing. However, I think there should be some problem with this line of code.
parseInt(price.value) += parseInt(50);
parseInt() is a function and you cannot assign values to it.
It should be some thing like this
price.value = parseInt(price.value) + parseInt(50);
Also price.value is not a proper reference because you are assigning document.getElementById("price").value; to it. So you should be using price instead of price.value

Categories