Javascript functions not calculating the fields - javascript

My javascript functions are not pulling the values from the input fields and performing the calculations. I am trying to create a form that:
1) allows input for start time, end time, and rate of pay,
2) calculates the total hours (start-end),
3) multiplies total hours by rate of pay to get the total pay for time period,
4) onclick returns the total pay as innerhtml.
I can't figure out why the function won't fetch the values from the html and perform the calculations. Any thoughts? I am a newbie at this. I tried adding the function to the onclick, I tried calling the function in the button, put the variables inside the function, pointing the button to the variable that holds the total, and 100 other things, and I'm still stuck.
<!DOCTYPE html>
<head>
<title> Babysitter Pay Calculator </title>
<script>
function calculate (enterAfternoonEndTime, enterAfternoonStartTime, enterAfternoonPayRate) {
return totalAfternoonPay;
var afternoonStartTime = document.getElementbyId("enterAfternoonStartTime").value;//military time
var afternoonEndTime = document.getElementbyId("enterAfternoonEndTime").value;
var afternoonPayRate = document.getElementbyId("enterAfternoonPayRate").value;
var totalAfternoonPay = (enterAfternoonEndTime - enterAfternoonStartTime) * enterAfternoonPayRate
}
</script>
</head>
<body>
<h1>Welcome to the Babysitter Calculator!</h1>
<p> Pay is calculated for the following shifts: </p>
<ul>
<li>Afternoon: 5:00pm - 8:00pm </li>
<li>Evening: 8:01pm - Midnight</li>
<li>Overnight: 12:01am - 4:00am</li>
</ul>
<p>
<label>Enter afternoon start time (i.e, 13:00 = 1pm):</label>
<input type = "number" name="enterAfteroonStartTime" id="enterAfteroonStartTime" />
</p>
<p>
<label>Enter afternoon end time:</label>
<input type = "number" name ="enterAfternoonEndTime" id = "enterAfternoonEndTime" />
</p>
<p>
<label>Enter afternoon pay rate:</label>
<input type = "number" name="enterAfternoonPayRate" id = "enterAfternoonPayRate"/>
</p>
<button type="button" onclick="function calculate"> Calculate! </button>
<p id = showcalculation>
<label> Total Pay Per Shift: </label>
<script> document.getElementbyId(var totalAfternoonPay).innerhtml = "totalAfternoonPay";</script>
</p>
</body>
</html>

You have a large number of errors in your code. Undeclared variables, incorrect use of the onClick, unexpected tokens. I made as few changes as possible to what you did to make it work, but there are some fundamentals you should work on here.
<!DOCTYPE html>
<html>
<head>
<title> Babysitter Pay Calculator </title>
<script>
function calculate() {
var afternoonStartTime = document.getElementById("enterAfteroonStartTime").value; //military time
var afternoonEndTime = document.getElementById("enterAfternoonEndTime").value;
var afternoonPayRate = document.getElementById("enterAfternoonPayRate").value;
var totalAfternoonPay = (afternoonEndTime - afternoonStartTime) * afternoonPayRate / 100;
document.getElementById('pay').innerText = totalAfternoonPay;
}
</script>
</head>
<body>
<h1>Welcome to the Babysitter Calculator!</h1>
<p> Pay is calculated for the following shifts: </p>
<ul>
<li>Afternoon: 5:00pm - 8:00pm </li>
<li>Evening: 8:01pm - Midnight</li>
<li>Overnight: 12:01am - 4:00am</li>
</ul>
<p>
<label>Enter afternoon start time (i.e, 13:00 = 1pm):</label>
<input type="number" name="enterAfteroonStartTime" id="enterAfteroonStartTime" />
</p>
<p>
<label>Enter afternoon end time:</label>
<input type="number" name="enterAfternoonEndTime" id="enterAfternoonEndTime" />
</p>
<p>
<label>Enter afternoon pay rate:</label>
<input type="number" name="enterAfternoonPayRate" id="enterAfternoonPayRate" />
</p>
<button type="button" onclick="calculate()"> Calculate! </button>
<p id=s howcalculation>
<label> Total Pay Per Shift: </label>
<span id="pay"></span>
</p>
</body>
</html>

Your code has a bunch of errors. I'll list some of them so you can see basically what's wrong:
<p id = showcalculation> should be <p id="showcalculation">
<button type="button" onclick="function calculate"> is wrong at the "onclick" attribute. You need to invoke the function, not redeclare it. It should be <button type="button" onclick="calculate();">
Your function is returning a value before making the calculation. return statement should be at end, when you're indeed returning something.
You are obtaining all the data that are required for calculation using document.getElementById to get the values. Using this, you don't need parameters anymore
document.getElementbyId(var totalAfternoonPay).innerhtml = "totalAfternoonPay"; is completely wrong. You need to pass the selector to getElementById function instead of declaring another variables on it. Check my snippet to see the correct way
Pay attention to casing. All functions are case-sensitive. document.getElementbyId won't work. The correct is document.getElementById.
Try to read some tutorials or read some books about programming. Going into it without having the basics won't make you understand the way to go. Also use some IDE's like VSCode or Visual Studio. It'll give you some advices about wrong written code and will save your time :)
<!DOCTYPE html>
<head>
<title> Babysitter Pay Calculator </title>
<script>
function calculate () {
var afternoonStartTime = document.getElementById("enterAfternoonStartTime").value;//military time
var afternoonEndTime = document.getElementById("enterAfternoonEndTime").value;
var afternoonPayRate = document.getElementById("enterAfternoonPayRate").value;
var totalAfternoonPay = (afternoonEndTime - afternoonStartTime) * afternoonPayRate
document.getElementById("totalAfternoonPay").innerHTML = totalAfternoonPay;
}
</script>
</head>
<body>
<h1>Welcome to the Babysitter Calculator!</h1>
<p> Pay is calculated for the following shifts: </p>
<ul>
<li>Afternoon: 5:00pm - 8:00pm </li>
<li>Evening: 8:01pm - Midnight</li>
<li>Overnight: 12:01am - 4:00am</li>
</ul>
<p>
<label>Enter afternoon start time (i.e, 13:00 = 1pm):</label>
<input type = "number" name="enterAfternoonStartTime" id="enterAfternoonStartTime" />
</p>
<p>
<label>Enter afternoon end time:</label>
<input type = "number" name ="enterAfternoonEndTime" id = "enterAfternoonEndTime" />
</p>
<p>
<label>Enter afternoon pay rate:</label>
<input type = "number" name="enterAfternoonPayRate" id = "enterAfternoonPayRate"/>
</p>
<p >
</p>
<button type="button" onclick="calculate();"> Calculate! </button>
<p id = "showcalculation">
<label> Total Pay Per Shift:<span id="totalAfternoonPay"></span> </label>
</p>
</body>
</html>

Related

I get NaN error when trying to create a basic calculator

I'm 3 days into learning Javascript and im really excited to understand more of this language, before i started i've done a basic HTML & CSS education. I'm currently on a 2 year program in a University in Sweden.
I'm trying to create a very basic calculator, that for now only adds 2 numbers together. I have 1 box, and another box. I want to make that each number written in each of these boxes is displayed as the total of box1, box2 in the third and final box.
At this moment i get "NaN" in the 3rd box when trying to add 2+3.
As i said, I'm really new and i appreciate all help i can get, and note that im not here for anyone to do my assignments which we have plenty of, i am really interessted in learning and understanding the language because i would like to work with this later in life when im done with my education.
Cheers!
<h1>Addera två tal med varandra</h1>
<form>
<input type="text" value="0" id="tal1" /> <br>
<input type="text" value="0" id="tal2" /> <br>
<input type="button" value="Beräkna" onClick="kalkylera();" />
<p>Den totala summan är</p>
<input type="text" value="0" id="svar" />
</form>
<script>
function kalkylera() {
//Get the two numbers entered in the box
var ForstaTalet = document.getElementById("tal1").value;
var AndraTalet = document.getElementById("tal2").value;
//Count the two entered numbers together
var svar = tal1 + tal2;
//Show result
document.getElementById("svar").value = svar;
}
</script>
PS, I'm not sure why "//# sourceURL=pen.js" is written i the bottom of the calculator when adding this to the codepen, that is not how it looks when viewing it in chrome.
Thanks in advance.
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>Calculator</title>
</head>
<body>
<form>
<input type="text" placeholder='num1' id="tal1"/> <br>
<input type="text" placeholder='num2' id="tal2"/> <br>
<input type="button" value="Add" onClick="sum()"/>
<input type="text" placeholder='sum' id="svar"/>
</form>
<script>
function sum()
{
var ForstaTalet = parseFloat(document.getElementById("tal1").value);
var AndraTalet = parseFloat(document.getElementById("tal2").value);
var svar = ForstaTalet + AndraTalet;
document.getElementById("svar").value = svar;
}
</script>
</body>
</html>
This works fine.
You need to cast your values as float with parseFloat and use the right variables as in the following example:
//Get the two numbers entered in the box
var ForstaTalet = parseFloat(document.getElementById("tal1").value);
var AndraTalet = parseFloat(document.getElementById("tal2").value);
//Count the two entered numbers together
var svar = ForstaTalet + AndraTalet;
//Show result
document.getElementById("svar").value = svar;

How to convert live javascript variables to php variables?

I'm extremely new to this so please excuse my spaghetti code - I'm trying to make a webpage that keeps track of basketball statistics live during a game, and then saves the total statistics using php afterwards. For now, I just need to pass the variable that is being live updated from my html page to php at the press of a button. I'm pretty sure I'm not even close, but am getting the 'undefined index' message when trying this. Here is my html page:
<head>
<meta charset="utf-8">
<title>Scoring</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
var points = 0;
var assists = 0;
var rebounds = 0;
function add1point(){
points++;
document.getElementById('displaypoints').innerHTML = '<p>Points: ' + points;
}
function add2points(){
points = points + 2;
document.getElementById('displaypoints').innerHTML = '<p>Points: ' + points;
}
function add3points(){
points = points + 3;
document.getElementById('displaypoints').innerHTML = '<p>Points: ' + points;
}
function add1assist(){
assists++;
document.getElementById('displayassists').innerHTML = '<p>Assists: ' + assists;
}
function add1rebound(){
rebounds++;
document.getElementById('displayrebounds').innerHTML = '<p>Rebounds: ' + rebounds;
}
</script>
</head>
<body>
<center>
<br>
<button onclick="add1point()">+1 Point (Made Free-Throw)</button>
<br>
<br>
<button onclick="add2points()">+2 Points (Made Field-Goal)</button>
<br>
<br>
<button onclick="add3points()">+3 Points (Made Three-Pointer)</button>
<br>
<br>
<br>
<button onclick="add1assist()">+1 Assist</button>
<br>
<br>
<br>
<button onclick="add1rebound()">+1 (Offensive) Rebound</button>
<br>
<br>
<button onclick="add1rebound()">+1 (Defensive) Rebound</button>
<br>
<br>
<br>
<br>
<form method="post" attribute="post" action="scoring.php">
<div id="displaypoints"><script type="text/javascript">document.write('<p>Points: ' + points);</script></div>
<div id="displayassists"><script type="text/javascript">document.write('<p>Assists: ' + assists);</script></div>
<div id="displayrebounds"><script type="text/javascript">document.write('<p>Rebounds: ' + rebounds);</script></div>
<br>
<br>
<br>
<input type="submit" name="finish" id="finish" value="Finish Game">
</button>
</form>
</center>
</body>
</html>
And my php code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Game Finished</title>
</head>
<body>
<?php
$points = $_POST['points'];
$assists= $_POST['assists'];
$rebounds = $_POST["rebounds"];
?>
</p>
</body>
Any help at all would be greatly appreciated :)
I rewrote some parts of your code. I hope you don't mind :).
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Scoring</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
</head>
<body>
<center>
<br>
<button onclick="addPoints(1)">+1 Point (Made Free-Throw)</button>
<br>
<br>
<button onclick="addPoints(2)">+2 Points (Made Field-Goal)</button>
<br>
<br>
<button onclick="addPoints(3)">+3 Points (Made Three-Pointer)</button>
<br>
<br>
<br>
<button onclick="addAssists(1)">+1 Assist</button>
<br>
<br>
<br>
<button onclick="addRebounds(1)">+1 (Offensive) Rebound</button>
<br>
<br>
<button onclick="addRebounds(1)">+1 (Defensive) Rebound</button>
<br>
<br>
<br>
<br>
<form method="post" attribute="post" action="scoring.php">
<p>Points: <span id="displaypoints"></span></p>
<p>Assists: <span id="displayassists"></span></p>
<p>Rebounds: <span id="displayrebounds"></span></p>
<!-- Any input element with "name" attribute will be sent to server (scoring.php script). -->
<input type="hidden" name="points" id="points" />
<!-- Any input element with "name" attribute will be sent to server (scoring.php script). -->
<input type="hidden" name="assists" id="assists" />
<!-- Any input element with "name" attribute will be sent to server (scoring.php script). -->
<input type="hidden" name="rebounds" id="rebounds" />
<br>
<br>
<br>
<input type="submit" name="finish" id="finish" value="Finish Game">
</form>
</center>
<script type="text/javascript">
// Initial values
var points = 0;
var assists = 0;
var rebounds = 0;
// Find "span" element with "displaypoints" id.
$displayPoints = $("#displaypoints");
// Set element text to initial points value.
$displayPoints.text(points);
// Find "span" element with "displayassists" id.
$displayAssists = $("#displayassists"),
// Set element text to initial assists value.
$displayAssists.text(assists);
// Find "span" element with "displayrebounds" id.
$displayRebounds = $("#displayrebounds");
// Set element text to initial rebounds value.
$displayRebounds.text(rebounds);
// Function that receives the amount of points.
// 1. Adds received amount of points to current amount of points.
// 2. Sets the corresponding element text to current amount of points.
// 3. Sets the element that's going to be sent to server value to current amount of points.
function addPoints(amount){
points += amount;
$displayPoints.text(points);
$("#points").val(points);
}
// Function that receives the amount of assists.
// 1. Adds received amount of assists to current amount of assists.
// 2. Sets the corresponding element text to current amount of assists.
// 3. Sets the element that's going to be sent to server value to current amount of assists.
function addAssists(amount){
assists += amount;
$displayAssists.text(assists);
$("#assists").val(assists);
}
// Function that receives the amount of rebounds.
// 1. Adds received amount of rebounds to current amount of rebounds.
// 2. Sets the corresponding element text to current amount of rebounds.
// 3. Sets the element that's going to be sent to server value to current amount of rebounds.
function addRebounds(amount){
rebounds += amount;
$displayRebounds.text(rebounds);
$("#rebounds").val(rebounds);
}
</script>
</body>
</html>
As James' comment said you could do it easily by inputs in your form. I guess you do not want that the user may change the value at the finish of the game, so you could use input hidden, something like this:
<form method="post" action="scoring.php">
<div id="displaypoints"><script type="text/javascript">document.write('<p>Points: ' + points+'</p><input type="hidden" name="points" value="'+points+'">');</script></div>
...
<input type="submit" name="finish" id="finish" value="Finish Game">

Max number pool input text from database and decrease it when pick to form html/js/php

Ok i have a little code to distribute point from pool in to stats made with form. my Code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="http://mynindo.pl/test/css/style.css">
<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js'></script>
<script src="http://mynindo.pl/test/js/incrementing.js"></script>
<link href="http://mynindo.pl/test/css/bootstrap.css" rel="stylesheet" media="screen">
</head>
<body>
<div class="well">
<div class="container">
<form method="post" action="">Points: 50<br /><br />
<label for="name">Int</label>
<div class="numbers-row"><input type="text" name="int" id="int" value="0">
</div>
<label for="name">Str</label>
<div class="numbers-row"><input type="text" name="men" id="men" value="0">
</div>
<label for="name">Dex</label>
<div class="numbers-row"><input type="text" name="dex" id="dex" value="0">
</div>
<label for="name">Dex2</label>
<div class="numbers-row"><input type="text" name="str" id="str" value="0">
</div>
<div class="buttons">
<input type="submit" value="Submit" id="submit">
</div>
</form>
</div></div>
</body>
</html>
My php code in app.php check if sum of all points $Post[] is == points pool. every works fine, but wieh user got meny poits for the distribute need math so can't be tricky.
And now my question, is this possible to change value of poits pool in real time with ajax or jquery? i mean, i got 50 points total i add 1 to Str (didn;t sumbit) and value pool changed from 50 to 49 w/o reloading page?
as you are not updating database until pressing submit button then just manipulating that span element will suffice,
put following code your html section instead of your corresponding code
Points: <span id="point" data-available="50">50</span>
Add following JavaScript code
$(':text').change(function(){
var total=0;
$( ":text" ).each(function( i ) {
total += parseInt($(this).val());
});
$('#point').html($('#point').data("available")-total);
});
this will do the trick.
BTW you should make sure input is number
I Tried to add Uoyr code reza but i'm not sure how, also i tried wrote my own script to count all those numbers but it also fail
function countNum(val) {
var sum = document.getElementById("sum").value;
var i = document.getElementById("int").value;
var w = document.getElementById("men").value;
var s = document.getElementById("dex").value;
var d = document.getElementById("str").value;
var points = i + w + s + d;
if ( points == 0){
$('#suma').text(0);
}else{
$('#suma').text(suma - points);
}};
with
Points: <div style="display: inline;" id="sum">50</div>
But didn't work at all. Cna you show me how ur code should work with my on snippet?

How to use a function in an external Javascript file in HTML?

This is my first time using an external Javascript file. I am doing the exercise in the murach series of books on Javascript and I am stuck on some pretty basic things. I will show the Javascript coding i did then i will show you the html file. Whenever I click the button to calculate the future value it does nothing even though I have the onload event handler.
/*Javascript*/
var $ = function(id) {
return document.getElementById(id);
};
function calculateFV(investment, interest, years) {]{
investment = $("investment").parseFloat($("investment").value);
interest = $("annual_rate").parseFloat($("annual_rate").value);
years = $("years").parseInt($("years").value);
var cInterest = investment * interest;
cInterest = parseFloat(cInterest);
futureValue = parseFloat(futureValue);
for (var i = 1; i < years; i++) {
investment = investment + (cInterest / 100);
}
investment = parseFloat(investment).toFixed(2);
$ ("future_value") = investment;
}
window.onload = function() {
$("calculate").onclick = calculateFV;
$("investment").focus();
};
/* End of Javascript */
/* HTML */
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Future Value Calculator</title>
<link rel="stylesheet" href="future_value.css">
<script src="future_value.js"></script>
</head>
<body>
<main>
<h1>Future Value Calculator</h1>
<label for="investment">Total Investment:</label>
<input type="text" id="investment">
<span id="investment_error"> </span><br>
<label for="rate">Annual Interest Rate:</label>
<input type="text" id="annual_rate">
<span id="rate_error"> </span><br>
<label for="years">Number of Years:</label>
<input type="text" id="years">
<span id="years_error"> </span><br>
<label for="future_value">Future Value:</label>
<input type="text" id="future_value" disabled><br>
<label> </label>
<input type="button" id="calculate" value="Calculate"><br>
</main>
</body>
</html>
/* End of HTML */
Regardless of the typographic errors in your code, there are some other mistakes you do I would like to mention:
parseInt() is a function; not a method. Therefore it must be used as a function. Like so: investment = parseFloat($("investment").value);
instead of:investment = $("investment").parseFloat($("investment").value);
$("future_value") is the textbox; not it's value. To actually have something appear in $("future_value"), you have to say: $("future_value").value = investment.
Your calculateFV() function should not have any parameters. Investment, interest and years are local variables inside the function, so your function doesn't require any input.
You parse too much and carelessly. In your code you say: cInterest = parseFloat(cInterest); and futureValue = parseFloat(futureValue);• We use parseFloat() to parse a string. The above variables contain arithmetic values that occurred after a mathematical operation and not strings. Therefore you do not need to parse them.
I created a jsFiddle with your code corrected and properly functioning. You can find it here.
Good luck in your learning process ☺

having trouble with javascript

Beginer to javasctipt. I am trying to write a simple calculation that will display some text if the time since oil change is past 6 months, the amount of oil left in the car is less then it started and finally display if everything is ok.
Thanks for the help
JavaScript
function oil(){
var start = document.oil.start.value;
var lastOilChange = document.oil.time.value;
var totalOil = document.oil.amount.value;
var aa = "you need to change the oil";
if( lastOilChange > 6 || start < totalOil){
document.oil.result.write(aa);
}else{
document.oil.result.write("Everything Is all good");
}
}
HTML
<form name="oil">
Starting amount of oil
<input type="text" name="start">
Time since oil change
<input type="text" name="time">
Total amount of oil in car now(quarts)
<input type="text" name="amount">
<input type="submit" onclick = oil()>
<input name=result readonly>
</form>
There are a couple of problems with your code
Missing Form close tag
Your controls don't have IDs
missing quotes on the result input
Don't need to use a submit input when you're not submitting to a form. Try button
Not sure what document.oil.result.write(aa); will do. I think the correct process is to get the input using document.getElementById and then set the value of the control
I will try to answer your question with the least number of line changes. This is not the optimal answer. Comments have been added to help you understand required changes. Your HTML and JavaScript are invalid, so it was a surprise to me how they both ran on Chrome.
<!doctype>
<html>
<head>
<title>Personal</title>
<meta charset="utf-8">
<script type="text/javascript">
function _oil(){ // oil() conflicts with your form's name
var start = document.oil.start.value;
var lastOilChange = document.oil.time.value;
var totalOil = document.oil.amount.value;
var aa = "you need to change the oil";
if( lastOilChange > 6 || start < totalOil){
document.write(aa); // you can't .write() to an element
}else{
document.write("Everything Is all good");
}
window.event.preventDefault(); // so your window does not load the same page when you submit
return false;
}
</script>
<style>
form input {
display: block;
}
</style>
</head>
<body>
<form name="oil">
Starting amount of oil
<input type="text" name="start">
Time since oil change
<input type="text" name="time">
Total amount of oil in car now(quarts)
<input type="text" name="amount">
<input type="submit" onclick ="_oil()"> <!-- you must enclose the onclick attribute, even if both work -->
<input name=result readonly>
</body>
</html>
May be like this:
<!doctype>
<html>
<head>
<title>Personal</title>
<meta charset="utf-8">
<script type="text/javascript">
function oil(){
var start = document.getElementsByName("start")[0].value;
var lastOilChange = document.getElementsByName("time")[0].value;
var totalOil = document.getElementsByName("amount")[0].value;
var aa = "you need to change the oil";
if( lastOilChange > 6 || start < totalOil){
document.getElementsByName("result")[0].value = aa;
}else{
document.getElementsByName("result")[0].value = "Everything Is all good";
}
}
</script>
<style>
form input {
display: block;
}
</style>
</head>
<body>
<form name="thisform">
Starting amount of oil
<input type="text" name="start">
Time since oil change
<input type="text" name="time">
Total amount of oil in car now(quarts)
<input type="text" name="amount">
<input type="button" value="go" onclick = oil()>
<input name=result readonly>
</form>
</body>
</html>
!!! The form name can not use oil
What you want is to set the value of the form field rather than trying to use write:
if( lastOilChange > 6 || start < totalOil){
document.oil.result.value = aa;
} else {
document.oil.result.value = "Everything Is all good";
}
As pointed out in other answers, though, you also need to prevent the form from trying to submit information to the server and reload the page. There are several ways of doing this (see e.g. JavaScript code to stop form submission). One is to replace the submit button with an ordinary button (<input type="button" value="Calculate" />).
Another is to attach your function to the form as an event handler, and return false at the end of it.
document.oil.onsubmit = function () {
...
return false;
}
(JSFiddle)

Categories