javascript read number of hours worked - javascript

Write the JavaScript to read the number of hours worked from the user. Then write the JavaScript to calculate how much money the user made if they were paid $12/hour for the first 40 hours worked, and $18/hr for all hours worked over 40. Then use the alert() function to print the total amount to the user.
what code do I have to use
var y = prompt("Enter a Value","");

Lol #OverComplicated. The answer is there just remake a better version and try your homework before being spoonfed.
var BarryScott = {
PricePerHour: 12,
HoursWorkedByBarry: 0,
PrintPayment: function() {
if ( this.HoursWorkedByBarry > 40) {
var RemainHours = this.HoursWorkedByBarry - 40;
alert(this.PricePerHour * 40 + RemainHours * 18);
} else {
alert(this.PricePerHour * this.HoursWorkedByBarry);
}
},
AskHoursFromBarry: function() {
this.HoursWorkedByBarry = prompt("Enter Hours you worked");
this.PrintPayment();
}
}
BarryScott.AskHoursFromBarry();

Create a folder and place your index.html and javascript code inside.
Run index.html .
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Im lazy to do my assignment</title>
<script src = "billhours.js"></script>
</head>
<body>
</body>
</html>
billhours.js
var getInput = prompt("Enter Number of Hours worked");
var first40hrs = billHours(40, 12);
var over40hrs = billHours(getInput - 40, 18);
var totalSalary = first40hrs + over40hrs;
alert("Total Salary is "+totalSalary);
function billHours(hours, rate){
return hours*rate;
}
//This function only works for hours 40 and above.
//It's your job to put conditional statements if hours is below 40. Keep Coding.

Related

How can I add a thousands separator in those lines of code?

I have been googling for this, but I found the solutions difficult, so I came here to ask how can I do it.
I'm doing an incremental game and I want to start with the basics: mining gold and buying. Now I'm moving to my next step at developing this game and I really need help
HTML
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Gold Miner</title>
</head>
<body>
<h2 id="goldMined">0 Gold Mined</h2>
<br />
<br />
<button onclick="buyGoldPerClick()" id="perClickUpgrade">Get More Money. Cost: 10 Gold</button>
<br />
<br />
<button onclick="Reset()">Reset Game</button>
<script src="main.js" charset="utf-8" type="text/javascript"></script>
</body>
</html>
JavaScript
var gameData = {
gold: 0,
goldPerClick: 0.01,
goldPerClickCost: 10,
tickReduction: 1000,
tickReductionCost: 100
}
function mineGold() {
gameData.gold += gameData.goldPerClick
document.getElementById("goldMined").innerHTML = gameData.gold.toFixed(0).toLocaleString('en') + " Gold Mined"
document.getElementById("perClickUpgrade").innerHTML = "Buy Pickaxe. Cost: " + gameData.goldPerClickCost.toFixed(0).toLocaleString('en') + " Gold"
}
function buyGoldPerClick() {
if (gameData.gold >= gameData.goldPerClickCost) {
gameData.gold -= gameData.goldPerClickCost
gameData.goldPerClick *= 2
gameData.goldPerClickCost *= 3
document.getElementById("goldMined").innerHTML = gameData.gold.toLocaleString('en') + " Gold Mined"
document.getElementById("perClickUpgrade").innerHTML = "Buy Pickaxe. Cost: " + gameData.goldPerClickCost.toLocaleString('en') + " Gold"
}
}
function Reset() {
gameData.gold = 0
gameData.goldPerClick = 0.01
gameData.goldPerClickCost = 10
}
var mainGameLoop = window.setInterval(function () {
mineGold()
}, 10)
var saveGameLoop = window.setInterval(function () {
localStorage.setItem("goldMinerSave", JSON.stringify(gameData))
}, 1)
var savegame = JSON.parse(localStorage.getItem("goldMinerSave"))
if (savegame !== null) {
gameData = savegame
}
Any help supports a lot for me, as I am a JavaScript and HTML programming beginner! Thanks for reading my post!
You can use the NumberFormat() function from the Intl API available in Javascript. (click on the link for documentation).
The first parameter to the Intl.NumberFormat() function is the locale, if you want it to be generic, just pass in 'en-US'. But if you can also pass in navigator.language if you want to just take the language from the browser.
The second parameter to this function is an options object. Now, within this options object, I have passed in the maximumSignificantDigits and set it to 3. You can change that as per your requirements. You also have other options you can pass in, just check out the link I provided above.
Finally, you will be calling the format() function and passing in your gold as the parameter, and this will overall return you the formatted value with 3 maximum significant digits.
const gold = 1000000;
const formattedGold = Intl.NumberFormat('en-US', { maximumSignificantDigits: 3 }).format(gold);
//Printing output to console
console.log(formattedGold);

How to setup a while loop with variables

I'm wanting to setup a while loop in heading 1 that allows a user to input three employees names with hours worked, hourly wage, and total pay. The loop needs to calculate those, account for overtime (over 40 hours receives 1.5x pay for any hours over 40), and display all three employees information after calculating.
What do I need to fix with my code to achieve the desired result?
I've referred to W3Schools and Youtube on "Creating a while loop" and "Declaring variables".
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
<meta charset="ISO-8859-1">
<title>JavaScript Page</title>
<script language="javascript">
"<h1> Martha's Diner</h1>"
// Variables get declared
var employeeCount; employeeCount = "3";
var hoursWorked; hoursWorked = " ";
var hourlyWage; hourlyWage = " ";
var notOvertime; notOvertime = "<=40";
var overTime; Overtime = ">40";
var totalPay; totalPay = "overTime + notOvertime";
var employeeName = " ";
var i = 0;
/// While Loop
while (i < employeeCount) {
employeeName = window.prompt ("Enter an Employee Name");
hoursWorked = window.prompt ("Enter Hours Worked");
hourlyWage = window.prompt ("Enter Hourly Wage");
if (hoursWorked <= 40)
hourlyWage * hoursWorked;
i++
}
</script>
</head>
<body>
</body>
</html>
I expected the loop to end and calculate keyed information, but the loop doesn't stop or calculate at all.
you are running an infinite while loop as any positive integer in java or javascript takes as true and check your closing loop braces.To input three values using while you can try like this:
var a=0;
while(a<3)
{
//your codes
//your codes
a=a+1;
}
this will execute 3 times

How to set a cache with Local Storage

I have a ads box and i want close it to by clicking x button so after it has been closed i don't want to se it until 24 hours with cache I created a localstorage but it's not working as i expected how should i edit my example
var showCase = Math.round(+new Date() / 1000);
document.getElementById("close_ads").addEventListener("click", function () {
if (typeof localStorage.showCase == 'undefined' || parseInt(localStorage.showCase) <= (showCase - 3600)) {
localStorage.showCase = showCase;
document.getElementById('reklam_box').style.display = 'none';
}
});
<div id="ads_box">
Hi..I am a ads..
<span id="close_ads">Close ads and don't show unit for 24 hours</span>
</div>
You need to use Localstorages .setItem() and .getItem check this out.
https://www.taniarascia.com/how-to-use-local-storage-with-javascript/
So something like this
// set the item
localStorage.setItem('showCase', 3600);
//get the item
var showCase = localStorage.getItem('showCase');
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example</title>
</head>
<body>
<div id="ads_box">
Hi..I am a ads..
<span id="close_ads">Close ads and don't show unit for 24 hours</span>
</div>
<script>
var dontShowUntil = new Date(new Date().getTime() + 60 * 60 * 24 * 1000);
document.getElementById("close_ads").addEventListener("click", function () {
localStorage.dontShowUntil = dontShowUntil;
document.getElementById('ads_box').style.display = 'none';
});
if (new Date(localStorage.dontShowUntil) > new Date()) {
document.getElementById('ads_box').style.display = 'none';
}
</script>
</body>
</html>
useful linkes:
https://johnresig.com/blog/dom-storage/
https://developer.mozilla.org/en-US/docs/Web/API/Storage
NOTICE : when working with localStorage with array of objects you must save it like that:
Just convert the objects to JSON strings:
localStorage.setItem("savedData", JSON.stringify(objects));
var objects = JSON.parse(localStorage.getItem("savedData")));

Can't get JavaScript output on website

The website is supposed to display a message counting down to the tax day. I can't seem to get anything to display on the page. The scrollbar doesn't even show up with the color even though I put in the write code. Some advice please.
<!DOCTYPE HTML>
<html>
<head><meta charset="utf-8">
<title>TaxDay</title>
<script type="text/javascript">
<!-- Hide from old browsers
function scrollColor() {
styleObject=document.getElementsByTagName('html')[0].style
styleObject.scrollbarFaceColor="#857040"
styleObject.scrollbarTrackColor="#f4efe9"
}
function countDown() {
var today = new Date()
var day of week = today.toLocaleString()
dayLocate = dayofweek.indexOf(" ")
weekDay = dayofweek.substring(0, dayLocate)
newDay = dayofweek.substring(dayLocate)
dateLocate = newday.indexOf(",")
monthDate = newDay.substring(0, dateLocate+1)}
yearLocate = dayofweek.indexOf("2016")
year = dayofweek.substr(yearLocate, 4)
var taxDate = new Date ("April 16, 2017")
var daysToGo = taxDate.getTime()-today.getTime()
var daysToTaxDate = Math.ceil(daysToGo/(1000*60*60*24))
function taxmessage() {
var lastModDate = document.lastModified
var lastModDate = lastModDate.substring(0,10)
taxDay.innerHTML = "<p style='font-size:12pt; font-
family:helvetica;'>Today is "+weekDay+" "+monthDate+" "+year+".
You have "+daysToTaxDate+" days to file your taxes.</p>"
}
}
//-->
</script>
The <div> id is taxDay if it's relevant. The body onLoad event handlers are scrollColor(); countDown(); and taxmessage().
you are not closing the countdown() function before the taxmessage() function - meaning that taxmessage is nested within countdown(). Also you do not have semicolons ";" after each line of the js. You should rewrite the code to either include the function of taxmessage() or close out countdown() first and call taxmessage with arguments passed to get the date variables.
check your console for errors

combining javascript and html

Design and code a program which prompts a user for the year they were born, calculates the user's age and displays the user's age. If the user's age is over 40 then set the background color of the web page to red. The solution must use the JavaScript Date object and use programmer created functions for calculating the user's age.
pretty small problem i just need to make the screen turn red if age is more then 40 I just cant seem to make that happen...
<html>
<head>
<title> Age of person </title>
<div id="age"></div>
<body>
<script>
function determine_age_of_person ( year )
{
var today = new Date();
var now_year = today.getFullYear();
var age = now_year - year_person_was_born;
return age;
}
var year_person_was_born;
//unsure about below statement the '==' part
var age_of_person==age;
do
{
year_person_was_born = prompt("Enter year you were born", "");
year_person_was_born = parseInt (year_person_was_born1 );
}
while (is(year_person_was_born));
age_of_person = determine_age_of_person ( year_person_was_born );
if (age_of_person>40)
document.body.style.backgroundColor = "red";
else
document.body.style.backgroundColor = "white";
document.getElementById("age").innerHTML = "You are " + age_of_person + " years old";
</script>
</body>
</html>
Ok there are lot of code placement issues here (you have an html element outside of the body element, return statements outside of functions, function arguments that you don't use). Here is a simplified version of what you are building (demo)
<html>
<head>
<title> Age of person </title>
</head>
<body>
<div id="age"></div>
<script>
function determine_age_of_person (year) {
return (new Date()).getFullYear() - year;
}
var age_of_person = determine_age_of_person(parseInt (prompt("Enter year you were born", ""), 10));
if (age_of_person>40) {
document.body.style.backgroundColor = "red";
} else {
document.body.style.backgroundColor = "white";
}
document.getElementById("age").innerHTML = "You are " + age_of_person + " years old";
</script>
</body>
</html>
Here is breakdown of the changes I made:
Moved <div id="age"></div> inside the body
Used argument year in determine_age_of_person() instead of global variable
Combined prompt, parseInt and determine_age_of_person into one line (and added a radix to parseInt, because JavaScript has weird rules related to non base 10 numbers, it's a good habit to get into)
Added curly braces to if statement
Removed useless code like do() and while()
change
if (year_person_was_born > 40)
to
if (age_of_person > 40)

Categories

Resources