Hi I unable to connect my javascript file to html. I tried coding everything and now I am unable to see changes in HTML. I am here trying to calculate the tax rate of employees with their overtime worked with tax deduction .
Thanks in advance. Please help.
My code for html is
<!doctype html>
<html>
<head>
<script language="JavaScript" src="employees.js"></script>
<link rel="stylesheet" type="text/css" href="employees.css" />
<title>Pay Form</title>
</head>
<body>
<section id="content">
<h1>
Employee Payroll Entry Form
</h1>
<div id="payForm">
<p>
<label for="fullName">Full Name:</label><input type="text" autofocus id="fullName" />
</p>
<p>
<label for="hoursWorked">Hours Worked:</label><input type="text" id="hoursWorked" />
</p>
<p>
<label for="hourlyRate">Hourly Rate:</label><input type="text" id="hourlyRate" />
</p>
<footer>
<button id="calculateButton" onclick="calculate()">Calculate</button>
</footer>
</div>
<h1>
Employee Payroll Summary Report
</h1>
<table id = "employees">
<tr>
<th>Employee Name</th>
<th>Gross Pay</th>
<th>Tax</th>
<th>Net Pay</th>
</tr>
</table>
</section>
</body>
and my javascript is
var fname = document.getElementById("fullName");
var hours = document.getElementById("hoursWorked");
var rate = document.getElementById("hourlyRate");
var table = document.getElementById("employees");
var gross;
var net;
var tax;
var overtime;
function grosspay() {
if (hours > 0 && hours < 40) {
gross = hours * rate;
} else if (hours < 40) {
overtime = hours - 40;
gross = (40 * rate) + (overtime * (rate * 1.5));
}
}
function taxPay() {
if (gross < 250) {
tax = gross * 0.25;
} else if (gross >= 250 && gross < 500) {
tax = gross * 0.30;
} else if (gross >= 500 && gross < 750) {
tax = gross * 0.40;
} else if (gross > 750) {
tax = gross * 0.50;
}
}
function netPay() {
net = gross - tax;
}
function calculate() {
if (hours > 0)
{
var row = table.insertRow();
var fnamecell = row.insertCell(0);
var grossPaycell = row.insertCell(1);
var taxCell = row.insertCell(2);
var netPayCell = row.insertCell(3);
grosspay();
taxPay();
netPay();
fnamecell.innerHTML = fname;
grossPaycell.innerHTML = grosspay;
taxCell.innerHTML = tax;
netPayCell.innerHTML = net;
}
}
function load() {
var calculateButton = document.getElementById("calculateButtom");
calculateButton.addEventListener("click", calculate);
}
you are get the elements like "hours" but not its value.
Please try the following calculate function and if still got problem please post the debugger output so that others can help you.
function calculate() {
var hoursValue = hours.value;
console.log("Hours are : " + hoursValue );
if (hoursValue > 0)
{
var row = table.insertRow();
var fnamecell = row.insertCell(0);
var grossPaycell = row.insertCell(1);
var taxCell = row.insertCell(2);
var netPayCell = row.insertCell(3);
grosspay();
taxPay();
netPay();
fnamecell.innerHTML = fname;
grossPaycell.innerHTML = grosspay;
taxCell.innerHTML = tax;
netPayCell.innerHTML = net;
}
}
you are get the elements but not its value.
get the values of input fields like:
var hours = document.getElementById("hoursWorked").value;
var rate = document.getElementById("hourlyRate").value;
and also move script tag to the bottom of the page inside body tag.
Related
I thought I had everything correct and I still can't seem to figure out why the function isn't working out the way it is supposed to. I have this issue where the code is having a reference error but I'm not sure how to define the function. I also put it through the W3 validator but that's not telling me anything.
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>discount amount</title>
</head>
<body>
<script>
/* Input: purchase amount
* Processing: determine through if statements if they get a discount
* Output: final price after tax
*/
// Computes and returns a discounted purchase amount.
function getDiscountedAmount(purchase) {
var purchase =
parseInt(document.getElementById('purchase').value);
var dayOfWeek = new Date().getDay();
var output = document.querySelector("#output");
let rate;
if (purchase < 50) {
rate = 0.06;
} else if (purchase < 100 && [2, 3].includes(dayOfWeek)) {
rate = 0.06;
} else if (purchase < 500 && [2, 3].includes(dayOfWeek)) {
rate = 0.06;
}
let discount = purchase * rate;
return purchase - discount;
output.innerHTML = "$" + String(getDiscountedAmount(200));
}
</script>
Please enter your final price: <input type="text" id="purchase" size="5">
<br>
<button type="button" onclick="getDiscountedAmount(purchase)">discount?
</button>
<div id="output"></div>
</body>
</html>
The first line of your function already is wrong, you're trying to get a float number from nothing and you're overriding your input parameter to the function
var purchase = parseFloat();
Try:
purchase = parseFloat(purchase);
so that it uses your input parameter.
Also I'm not too sure about your date comparison dayOfWeek == (2, 3), I don't know if that works, I've never seen that before, I personally use [2, 3].includes(dayOfWeek)
And lastly your function returns a value but then you don't see that value anywhere, try using
console.log(getDiscountedAmount(200)) or whatever your price is
In terms of your input and output you want to use DOM manipulation to get the input and show the output.
If you want to see the value in your "output" then
var output = document.querySelector("#output");
output.innerHTML = "$" + String(getDiscountedAmount(200));
Would be a simple DOM mechanism, but it's not the cleanest
One more tip is to put your script tags lastly in the body, because you want all your HTML elements "defined" first before you try to access them
Altogether a cleaner version of your code:
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>discount amount</title>
</head>
<body>
Please enter your final price: <input type="text" id="myInput" size="5" /><br />
<button type="button" id="myButton">discount?</button>
<div id="myOutput"></div>
<script>
var myInput = document.querySelector("#myInput");
var myOutput = document.querySelector("#myOutput");
var myButton = document.querySelector("#myButton");
myButton.onclick = function() {
// Computes and returns a discounted purchase amount.
var purchase = parseFloat(myInput.value);
var dayOfWeek = new Date().getDay();
var rate;
if (purchase < 50) {
rate = 0.06;
} else if (purchase < 100 && [2, 3].includes(dayOfWeek)) {
rate = 0.06;
} else if (purchase < 1000) {
rate = 0.025;
} else {
rate = 0.03;
}
let discount = purchase * rate;
var finalPrice = purchase - discount;
output.innerHTML = "$" + String(finalPrice);
};
</script>
</body>
</html>
I changed around some ID's and moved the onclick into your JavaScript for cleaner code overall, as we like to separate the HTML from the JS
When you load your script you get an Uncaught SyntaxError because you closed your function with two }. To fix this just delete line 31.
In your first line of the function you are using parseFloat(); wrong:
var purchase = parseFloat();
Do:
var purchase = parseFloat(purchase);
Than you need to get your input number.
getDiscountedAmount(purchase) in the onclick event doesn't work.
You can use this:
var purchase = document.getElementById("purchase").value; // get value from text field
purchase = parseFloat(purchase); // convert to float
In the end you have to do this to show the number in you output div:
let output = purchase - discount;
document.getElementById("output").innerText = output; // set discont into your output div
return output;
Here is your code and how i fixed it:
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>discount amount</title>
<script>
/* Input: purchase amount
* Processing: determine through if statements if they get a discount
* Output: final price after tax
*/
// Computes and returns a discounted purchase amount.
function getDiscountedAmount(purchase) {
var purchase = document.getElementById("purchase").value; // get value from text field
purchase = parseFloat(purchase); // convert to float
var dayOfWeek = new Date().getDay();
var rate;
if (purchase < 50) {
rate = 0.06;
}
else if (purchase < 100 && dayOfWeek ==(2,3)) {
rate = 0.06;
}
else if (purchase < 1000) {
rate = 0.025;
}
else {
rate = 0.03;
}
let discount = purchase * rate;
let output = purchase - discount;
document.getElementById("output").innerText = output; // set discont into your output div
return output;
}
</script>
</head>
<body>
Please enter your final price: <input type="text" id="purchase" size="5"><be>
<button type="button" onclick="getDiscountedAmount()">discount?</button>
<div id="output"></div>
</body>
</html>
I didn't change your return statement and dayOfWeek because i don't know how you exactly want to use it.
Here is what you are looking for:
body{margin:0;padding:0;font-family:arial;background:rgb(30,30,30);height:100vh;width:100%}.wrapper{background:lightgrey;background:linear-gradient(318deg,rgba(217,123,123,1) 0%,rgba(135,249,255,1) 100%);width:80%;height:126px;position:relative;top:calc(50vh - 63px);left:10%;padding:3px;border-radius:12px}.content{background:rgb(80,80,80);background:rgba(0,0,0,.5);border-radius:10px;width:calc(100% - 24px);padding:12px}label{font-weight:700;color:#fff}input{width:calc(100% - 16px);margin-top:4px;padding:6px;border:2px solid #fff;border:2px solid rgba(0,0,0,.3);color:#fff;background:#fff;background:rgba(0,0,0,.5);border-radius:6px;font-size:14pt}::placeholder{color:#fff;color:rgba(255,255,255,.8)}input:focus{outline:none;border:2px solid #fff;border:3px solid rgba(0,0,0,.6);padding:5px}.output-container{display:inline-block;float:right;width:180px;padding:8px;color:#fff;background:#fff;background:rgba(0,0,0,.5);font-size:12pt;margin-top:4px;border-radius:6px;font-size:14pt}button{margin-top:4px;width:150px;border:0;border-radius:6px;padding:8px;background:gray;background:rgba(0,0,0,.6);color:#fff;font-weight:700;font-size:14pt;transition:0.25s ease}button:focus{outline:none;}button:hover{cursor:pointer;background:gray;background:rgba(0,0,0,.8)}#media only screen and (max-width:400px){.wrapper{width:calc(100% - 6px);height:auto;top:0;left:0;border-radius:0}.output-container,button{width:calc(50% - 12px)}}
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>discount amount</title>
</head>
<body>
<div class='wrapper'>
<div class='content'>
<label>Please enter your final price:</label><input type="text" autocomplete="off" placeholder='Enter price...' id="purchase" size="5">
<button type="button" onclick="getDiscountedAmount()">See discount</button>
<div class='output-container'>Total: <span id='output'>--</span></div>
</div>
</div>
<script>
//Get the output element
outputEl = document.getElementById("output");
function getDiscountedAmount() {
//Gets the value of your input
var purchase = parseFloat((document.getElementById('purchase').value).replace(/[^\d]/g,""));
var dayOfWeek = new Date().getDay();
var rate;
if (purchase < 50) {
rate = 0.06;
} else if (purchase < 100 && [2, 3].includes(dayOfWeek)) {
rate = 0.06;
} else if (purchase < 500 && [2, 3].includes(dayOfWeek)) {
rate = 0.06;
}
else {
rate = 0.03;
}
let discount = purchase * rate;
let output = purchase - discount;
//Checks if output is a number.
if(isNaN(output)){
output = 'Not a number!';
} else{
output = '$' + output;
}
//Puts the output inside of your "output" <div>
outputEl.textContent = output;
}
</script>
</body>
</html>
I have two javascript functions called CalculateFV() which is used to calculate my future value by grabbing the inputs from the processEntries() function and then display the result in the future_value text box on the HTML page but I currently cannot see why it is not functioning correctly and the button is not working to calculate my result
I am also using atom as my editor
<!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"><br>
<label for="rate">Annual Interest Rate:</label>
<input type="text" id="rate">%<br>
<label for="years">Number of Years:</label>
<input type="text" id="years"><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>
var $ = function(id) {
return document.getElementById(id);
};
var calculateFV = function(investment_amount, interest_rate, number_of_years){
var futureValue;
futureValue = investment_amount
for(var i = 1; i <= number_of_years; i++){
futureValue = futureValue + (futureValue * interest_rate / 100);
}
return futureValue;
}
var processEntries = function(){
var investment_amount = $("investment").value;
var interest_rate = $("rate").value;
var number_of_years = $("years").value;
$("future_value").value = calculateFV(investment_amount, interest_rate, number_of_years);
}
window.onLoad = function(){
$("calculate").value = processEntries;
$("investment").focus();
}
The onLoad function wasn't being handled correctly and you need to register a click listener on the calculate button. Try this:
future_value.js:
"use strict";
var $ = function(id) {
return document.getElementById(id);
};
var calculateFV = function(investment_amount, interest_rate, number_of_years){
var futureValue;
futureValue = investment_amount
for(var i = 1; i <= number_of_years; i++){
futureValue = futureValue + (futureValue * interest_rate / 100);
}
return futureValue;
}
var processEntries = function(){
var investment_amount = $("investment").value;
var interest_rate = $("rate").value;
var number_of_years = $("years").value;
$("future_value").value = calculateFV(investment_amount, interest_rate, number_of_years);
}
window.addEventListener('load', (event) => {
$('calculate').addEventListener('click', processEntries);
$("investment").focus();
});
Using this I see the future value input populated after I click calculate. Note the changes I made towards the bottom.
I faced a problem for my code and I could not solve it. I have 2 functions, the first one calculates the total and second one discounts the total (if the user write the discount code, it will show the discounted total). But I don't know how to get and call the right value from total to keep it in the second function to calculate the discount because it always shows 0 in the amount. The TOTAL is for the first function and JavaScript code is for the second function.
total = parseInt(TicketsPrice[i].value) * parseInt(NOfTictet);
document.getElementById("total").innerHTML = total;
function discount(coupon) {
var yCoupon = "winner1";
var price = Number(document.getElementById('total').innerHTML);
var amount;
var input = document.getElementById('discount').value;
if (input == coupon) {
amount = price || 0 * 0.25;
document.getElementById("Offerprice").innerHTML = amount;
} else {
alert("Invalid");
}
}
<input type="text" name="coupon" id="discount">
<button onclick="discount()">discount</button>
<p id="total"></p>
<p><span id="Offerprice"></span></p>
Something like this?
function discount() {
var coupon = "winner1";
var price = Number(document.getElementById('total').value);
var input = document.getElementById('discount').value;
if (input == coupon) {
var amount = price * (1 - .25) // 25% off coupon
document.getElementById("Offerprice").innerHTML = amount;
} else {
document.getElementById("Offerprice").innerHTML = 'Invalid coupon'
}
}
<div>Total: <input id="total"></div>
<div>Coupon: <input id="discount"></div>
<button onclick="discount()"> discount</button>
<p><span id ="Offerprice"></span></p>
You have several issues in your code. Here is a working version. I hardcoded the total only for testing because I don't know the HTML for your tickets:
var total = 500; //This is only for testing.
document.getElementById("total").innerHTML = total;
function discount() {
var coupon = "winner1";
var price = Number(document.getElementById('total').innerHTML);
var input = document.getElementById('discount').value;
if (input == coupon) {
var amount = price * 0.75; //discount of 25%
document.getElementById("Offerprice").innerHTML = amount;
} else {
alert("Invalid");
}
}
<input type="text" name="coupon" id="discount">
<button onclick="discount()">discount</button>
<p id="total"></p>
<p><span id="Offerprice"></span></p>
I have a personal time keeper I am putting together for work. We are allotted 50 minutes a week, and I wanted to make a fancy way of keeping track of that time.
I have a method that works:
<!DOCTYPE html>
<html lang="en">
<head>
<style>
#example1 {
background-color="#0CD6C7";
}
</style>
<div id="example2">
<meta charset="utf-8" />
<title> Personal Timer</title>
<script type="text/javascript">
function setTimes(info) {
var sel = info.split('|');
document.getElementById('time1').value = sel[0];
document.getElementById('time2').value = sel[1];
}
</script>
</head>
<body bgcolor="#0CD6C7">
<div id="example1">
<hr align="left" size="0.5" color="white" width="82%">
<br>
<font face="arial">
<input id="time1" value="50:00" size="5"> 50 minutes of personal time per week <br>
<input id="time2" value="ex: 2:36" onfocus="this.value=''" size="5"> Type in the length of your personal break<br>
<button onclick="document.getElementById('time1').value = timeAddSub('time1','time2',false)">Enter</button>
<script type="text/javascript">
// From: http://www.webdeveloper.com/forum/showthread.php?273699-add-2-fields-containing-time-values-in-hh-mm-format&daysprune=30
Number.prototype.padDigit = function() { return (this < 10) ? '0'+this : ''+this; }
function timeAddSub(id1, id2, flag) { // flag=true to add values and flag=false to subtract values
var tt1 = document.getElementById(id1).value; if (tt1 == '') { return ''; }
var t1 = tt1.split(':');
var tt2 = document.getElementById(id2).value; if (tt2 == '') { return ''; }
var t2 = tt2.split(':');
tt1 = Number(t1[0])*60+Number(t1[1]);
tt2 = Number(t2[0])*60+Number(t2[1]);
var diff = 0; if (flag) { diff = tt1 + tt2; } else { diff = tt1 - tt2; }
t1[0] = Math.abs(Math.floor(parseInt(diff / 60))).padDigit(); // form hours
t1[1] = Math.abs(diff % 60).padDigit(); // form minutes
var tt1 = ''; if (diff < 0) { tt1 = '-'; }
// check for negative value
return document.getElementById("time1").innerHTML = tt1+t1.join(':');
}
</script>
</font>
</body>
</div>
</html>
Enter in the length of the break in the second input field and that time is subtracted from the total.
To make it look fancier, I want the total time to appear as only text, not as an input field.
This is what I have so far:
<!DOCTYPE html>
<html lang="en">
<head>
<style>
</style>
<div id="example2">
<meta charset="utf-8" />
<title> Personal Timer</title>
<script type="text/javascript">
function setTimes(info) {
var sel = info.split('|');
document.getElementById('time1').innerHTML = sel[0];
document.getElementById('time2').value = sel[1];
}
</script>
</head>
<body bgcolor="#0CD6C7">
<div id="example1">
<hr align="left" size="0.5" color="white" width="82%">
<br>
<font size="60" face="verdana" color="white">
<p id="time1"><font size="80"><b>50:00</b></p>
<font size="3" face="verdana">
<input id="time2" value="ex: 2:36" onfocus="this.value=''" size="5"> Type in the length of your break<br>
<button onclick="document.getElementById('time1').value = timeAddSub('time1', 'time2', false)">Enter</button>
<script type="text/javascript">
// From: http://www.webdeveloper.com/forum/showthread.php?273699-add-2-fields-containing-time-values-in-hh-mm-format&daysprune=30
Number.prototype.padDigit = function() {
return (this < 10) ? '0'+this : ''+this;
}
function timeAddSub(id1, id2, flag) { // flag=true to add values and flag=false to subtract values
var tt1 = document.getElementById(id1).value; if (tt1 == '') { return ''; }
var t1 = tt1.split(':');
var tt2 = document.getElementById(id2).value; if (tt2 == '') { return ''; }
var t2 = tt2.split(':');
tt1 = Number(t1[0])*60+Number(t1[1]);
tt2 = Number(t2[0])*60+Number(t2[1]);
var diff = 0; if (flag) { diff = tt1 + tt2; } else { diff = tt1 - tt2; }
t1[1] = Math.abs(diff % 60).padDigit(); // form minutes
t1[0] = Math.abs(Math.floor(parseInt(diff / 60))).padDigit(); // form hours
var tt1 = ''; if (diff < 0) { tt1 = '-'; }
// check for negative value
return document.getElementById("time1").innerHTML = tt1+t1.join(':');
}
</script>
</font>
</body>
</div>
</html>
I know I need to use innerHTML, but it's just not quite clicking. Any pointers in the right direction would be much appreciated!
Change the below line
var tt1 = document.getElementById(id1).value;
to
var p = document.getElementById(id1);
var tt1 = p.textContent;
This is because, value function is applicable only to input tags. For the other plain text tags like p, headings, etc. textContent should be fetched.
What wrong is since t1 is a p tag, it doesn't have value so tt1.split(':'); will throw an exception. Use innerText instead.
<!DOCTYPE html>
<html lang="en">
<head>
<style>
</style>
<div id="example2">
<meta charset="utf-8" />
<title> Personal Timer</title>
<script type="text/javascript">
function setTimes(info) {
var sel = info.split('|');
document.getElementById('time1').innerHTML = sel[0];
document.getElementById('time2').value = sel[1];
}
</script>
</head>
<body bgcolor="#0CD6C7">
<div id="example1">
<hr align="left" size="0.5" color="white" width="82%">
<br>
<font size="60" face="verdana" color="white">
<p id="time1"><font size="80"><b>50:00</b></p>
<font size="3" face="verdana">
<input id="time2" value="ex: 2:36" onfocus="this.value=''" size="5"> Type in the length of your break<br>
<button onclick="document.getElementById('time1').value = timeAddSub('time1', 'time2', false)">Enter</button>
<script type="text/javascript">
// From: http://www.webdeveloper.com/forum/showthread.php?273699-add-2-fields-containing-time-values-in-hh-mm-format&daysprune=30
Number.prototype.padDigit = function() {
return (this < 10) ? '0'+this : ''+this;
}
function timeAddSub(id1, id2, flag) { // flag=true to add values and flag=false to subtract values
var tt1 = document.getElementById(id1).innerText;
if (tt1 == '') { return ''; }
var t1 = tt1.split(':');
var tt2 = document.getElementById(id2).value; if (tt2 == '') { return ''; }
var t2 = tt2.split(':');
tt1 = Number(t1[0])*60+Number(t1[1]);
tt2 = Number(t2[0])*60+Number(t2[1]);
var diff = 0;
if (flag) { diff = tt1 + tt2; } else { diff = tt1 - tt2; }
t1[1] = Math.abs(diff % 60).padDigit(); // form minutes
t1[0] = Math.abs(Math.floor(parseInt(diff / 60))).padDigit(); // form hours
var tt1 = ''; if (diff < 0) { tt1 = '-'; }
// check for negative value
return document.getElementById("time1").innerHTML = tt1+t1.join(':');
}
</script>
</font>
</body>
</div>
</html>
From the input on the HTML, the user inputs the employee name and a number of hours they worked. From here on the submit button it takes the information and stores it in the variables so that I can calculate how much their pay was. Now with this also comes the overtime pay. I thought this was on the right track but whenever I go back to my HTML it displays "undefined". Any suggestions?
//Global Variables
var employeeName = document.getElementById("name").value;
var employeeHours = document.getElementById("hours").value;
function paySalary() {
if (employeeHours <= 40) {
var regtime = 11.00 * employeeHours;
var overtime = 0.00;
var salary = regtime;
} else if (employeeHours > 40) {
var regtime = (11.00 * 40);
var overtime = ((11.00 * 1.5) * (employeeHours - 40));
var salary = (regtime + overtime);
}
document.getElementById("results").innerHTML = "Employee Name: " + employeeName + " | Employee Gross Pay: " + salary;
}
//Event Listener to Submit
var submitButton = document.getElementById("submit");
if (submitButton.addEventListener) {
submitButton.addEventListener("click", paySalary, false);
} else if (submitButton.attachEvent) {
submitButton.attachEvent("onclick", paySalary);
}
Screenshot of output
Look at the scope of your salary variable, it's defined inside the if-else block. Make your salary variable accessible to document.getElementById() by declaring it in your function like this:
<html>
<script>
function paySalary() {
var employeeName = document.getElementById("name").value;
var employeeHours = document.getElementById("hours").value;
if (employeeHours <= 40) {
var regtime = 11.00 * employeeHours;
var overtime = 0.00;
var salary = regtime;
} else if (employeeHours > 40) {
var regtime = (11.00 * 40);
var overtime = ((11.00 * 1.5) * (employeeHours - 40));
var salary = (regtime + overtime);
}
document.getElementById("name").innerHTML = "Employee Name: " + employeeName;
document.getElementById("pay").innerHTML = "Employee Gross Pay: " + salary;
}
</script>
<body>
<input id="name" value="Kamesh Dashora"></input>
<input id="hours" value=40></input>
<br>
<span id="pay">0</span>
<br>
<button id="submit" onclick="paySalary()">Submit</button>
<body>
</html>