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
Related
Hello there!
I've been a given a Task like so:
Request the user to enter a number
Check if the user input is not empty. Also, check value entered is a number
Write on the HTML document a triangle out of the numbers as follow:
E.g. output: (let’s say the user entered number 10)
Your input number is 10.
10
11 11
12 12 12
13 13 13 13
14 14 14 14 14
15 15 15 15 15 15
The triangle should have 6 rows.
Use Comments explaining how the program works
Follow Indentation for clarity purposes.
Here is what I've tried so far:
var input = prompt("Enter a number: ");
if (input.value == '' || input.value == input.defaultValue) {
alert("Either you entered a NaN or you left an empty field. \nPlease enter some number!");
}
for (input = 10; input <= 15; input++) {
var a = '';
for (var j = 10; j <= input; j++) {
var a = a + '' + input;
}
document.writeln(a + "<BR>");
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Task Write your Own Code</title>
</head>
<body>
<h1>Task Write your Own Code</h1>
</body>
</html>
First of all, my IF statement is not working properly even if I input a string or don't leave a blank input field - the alert message still pop up;
And the result of document.writeln still printed even after alert pop's up with inputted string or empty field;
Please, someone, help me to solve this task or at least tell me what I'm doing wrong?
Thanks!
Look at the documentation for window.prompt().
Remove .value. input is the value.
Also, you aren't telling your code to not run if input is "bad".
// Be in a function so that you can return
(function() {
var input = prompt("Enter a number: ");
if (!input) {
alert("Either you entered a NaN or you left an empty field. \nPlease enter some number!");
// Get of of the function
return;
}
for (input = 10; input <= 15; input++) {
var a = '';
for (var j = 10; j <= input; j++) {
var a = a + '' + input;
}
document.writeln(a + "<BR>");
}
}());
|| input.value == input.defaultValue makes no sense since there is no such thing as input.defaultValue and, even if there was, you only need to check for an empty string. Also, input is already the response from the user so .value isn't needed.
You need to add an else condition to your if statement because even if no number is entered, your code will continue to do the looping.
Additionally, document.write() is only ever used in rare situations where you are building a new document from scratch, dynamically. It should not be used just to update an existing page's content. Instead, prepare an empty element ahead of time and when ready, update the content of that element.
Your loop configurations were a little off as well.
See other comments inline:
// Get the user's response, converted to a number
var input = parseInt(prompt("Enter a number: "), 10);
// Get a reference to the waiting output area on the page
var output = document.getElementById("output");
// Check that a number was given
if (!isNaN(input)) {
// We have a number...
// You know you need to go 6 times
for (x = 1; x < 7; x++) {
var a = '';
// And then you need to go however many times the outer loop is on
for (var j = 1; j <= x; j++) {
a += input + ' '; // You just need to write out the current input value
}
input++; // Increase the value
// Update the output area on the page
output.innerHTML += a + "<br>";
}
} else {
// We don't have a number:
alert("Either you entered a NaN or you left an empty field. \nPlease enter some number!");
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Task Write your Own Code</title>
</head>
<body>
<h1>Task Write your Own Code</h1>
<div id="output"></div>
</body>
</html>
And, if and when you get more into String operations, you'll find that you don't even need the inner loop:
// Get the user's response, converted to a number
var input = parseInt(prompt("Enter a number: "), 10);
// Get a reference to the waiting output area on the page
var output = document.getElementById("output");
// Check that a number was given
if (!isNaN(input)) {
// We have a number...
// You know you need to go 6 times
for (x = 1; x < 7; x++) {
// Set up the string to be written and then just repeat that
// however many times the outer loop is currently on.
output.innerHTML += (input + " ").repeat(x) + "<br>";
input++; // Increase the value
}
} else {
// We don't have a number:
alert("Either you entered a NaN or you left an empty field. \nPlease enter some number!");
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Task Write your Own Code</title>
</head>
<body>
<h1>Task Write your Own Code</h1>
<div id="output"></div>
</body>
</html>
I am having difficulty understanding a homework assignment. I would appreciate someone helping me with this matter. Please note I am not looking for someone to create the code for me, I am simply trying to understand why my code isn't working. This is the assignment:
Download the file below.
In the script element, add a do-while loop that prompts the user for an entry from 1 through 100. If the entry is invalid, display an
alert box with this message: “Please enter a number between 1 and
100”. Then, continue the loop until the entry is valid.
After the do-while loop, code a for loop that sums the numbers, and then display the second dialog box above. For instance, the sum for an
entry of four 1 + 2 + 3 + 4.
Add a do-while loop around all of the code that uses the third dialog box above to determine whether the first dialog box should be
displayed again so the user can enter another number. The application
should end for any entry other than “y”."
this is my code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sum of Numbers</title>
<script>
do
{
do
{
var theNumber = prompt("Enter first number", "10");
theNumber = parsInt(theNumber);
var numberOfLoops = (theNumber);
numberOfLoops = parsInt(numberOfLoops);
if(isNaN(theNumber) || theNumber <1 || theNumber > 100)
{
alert("Please enter a number between 1 and 100");
}
}
while (isNaN(theNumber) || theNumber <1 || theNumber > 100);
for (var counter = theNumber; counter>=1; counter--)
{
alert(counter);
}
sum == (theNumber + counter);
alert(sum);
again = prompt("Do it again? ('y' for yes)")
}
while(again = 'y');
</script>
</head>
<body>
<main>
<!-- Will show after JavaScript has run -->
<h1>Thanks for using the Sum of Numbers application!</h1>
</main>
</body>
</html>
I'm attempting to send emails using an HTML template.
I've looked at this post:
(https://stackoverflow.com/questions/33178702/passing-variables-into-html-code)
Would either of the two code examples be close to something that could work to pass the variables from the Javascript to the HTML template?
My javascript variables are named detail2, detail3, detail4, detail5 and detail6.
1st attempt:
<html>
<head>
<script>
{
var detail2 = document.getElementById("detail2").innerHTML;
var detail3 = document.getElementById("detail3").innerHTML;
var detail4 = document.getElementById("detail4").innerHTML;
var detail5 = document.getElementById("detail5").innerHTML;
var detail6 = document.getElementById("detail6").innerHTML;
}
}
</script>
</head>
<body>
<p>
<br>"Punctual? " document.getElementById('detail2').value<br>
<br>"Attention to detail? " document.getElementById('detail3').value<br>
<br>"Overall Professionalism? " document.getElementById('detail4').value<br>
<br>"Date of Service: " document.getElementById('detail5').value<br>
<br>"Notes/Details: " document.getElementById('detail6').value<br>
</p>
</body>
</html>
2nd attempt:
<html>
<head>
<script>
{
<input type="hidden" id="Detail2" value="detail2" />
<input type="hidden" id="Detail3" value="detail3" />
<input type="hidden" id="Detail4" value="detail4" />
<input type="hidden" id="Detail5" value="detail5" />
<input type="hidden" id="Detail6" value="detail6" />
}
}
</script>
</head>
<body>
<p>
<br>"Punctual? " document.getElementById('detail2').value<br>
<br>"Attention to detail? " document.getElementById('detail3').value<br>
<br>"Overall Professionalism? " document.getElementById('detail4').value<br>
<br>"Date of Service: " document.getElementById('detail5').value<br>
<br>"Notes/Details: " document.getElementById('detail6').value<br>
</p>
</body>
</html>
Finally, the method given on GAS Dev is below, but this only confuses me more. I am sure I've been at this too long and I'm burned out, I just can't seem to see the answer on this one.
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<table>
<? for (var i = 0; i < data.length; i++) { ?>
<tr>
<? for (var j = 0; j < data[i].length; j++) { ?>
<td><?= data[i][j] ?></td>
<? } ?>
</tr>
<? } ?>
</table>
</body>
</html>
If anyone can help it's much appreciated!
Below is the Javascript from the .gs script file.
function SendEmail() {
// initialize data
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var range = sheet.getDataRange();
var values = range.getValues();
// iteration loop
for (var i = 1; i<values.length; i++) {
// current times for comparator
var month = new Date().getMonth(); // returns today as 0-11 -- Jan is 0
var day = new Date().getDate(); // returns today as 1-31
var hour = new Date().getHours(); // returns today as 0-23
var minute = new Date().getMinutes(); // returns today as 0-59
// pull data from spreadsheet rows
var company = values[i][0];
var rating = values[i][1];
var detail1 = values[i][2];
var detail2 = values[i][3];
var detail3 = values[i][4];
var detail4 = values[i][5];
var detail5 = values[i][6];
var sendTime = values[i][7];
// character send times for comparator
var cSendMonth = sendTime.getMonth(); // returns sendMonth as 0-11 -- Jan is 0
var cSendDay = sendTime.getDate(); // returns sendDay as 1-31
var cSendHour = sendTime.getHours(); // returns sendHour as 0-23
var cSendMinute = sendTime.getMinutes(); // returns sendMinute as 0-59
// comparator
if(cSendMonth == month) {
if(cSendDay == day) {
if(cSendHour == hour) {
if(cSendMinute == minute) {
var htmlBody = HtmlService.createHtmlOutputFromFile('mail_template').getContent();
MailApp.sendEmail({
to: Session.getActiveUser().getEmail(),
subject: 'Test Email markup2 - ' + new Date(),
htmlBody: htmlBody,
});
} // end if minute test
}// end if hour test
}// end if day test
}// end if month test
}// end for loop
}
Can you try:
<html>
<head>
<script>
(function() {
var detail2 = document.getElementById("detail2").innerHTML;
document.getElementById("detail2_val").innerHTML = detail2;
})();
</script>
</head>
<body>
<p>
<br>"Punctual?" <span id="detail2_val"></span><br>
</p>
</body>
</html>
Currently, this line:
var htmlBody = HtmlService.createHtmlOutputFromFile('mail_template').getContent();
will not evaluate a template.
The method being used is:
createHtmlOutputFromFile('mail_template')
HtmlService has quite a few methods for creating html content. You need to use:
HtmlService.createTemplateFromFile(filename).evaluate()
There are some possible things that could go wrong in your overall work flow. If the situation is one in which you are writing data, and then immediately trying to read that same data that was just written, there could be a problem with the new data not being available to be read in such a short time span.
I would use:
SpreadsheetApp.flush();
immediately after writing the new data, and before creating the template.
Only your third html example has code for a template. To retrieve data and put it into a template, a scriptlet must either run a function, that then retrieves the data, or the data must be in global variables. The situation with global variable makes no sense, because you are using dynamic data, so a function would need to run to first put the data into a global variable. The function might as well just return the data directly. So, your scriptlet will probably need to run a server side function and return text or HTML to the html template. You probably need to use a printing scriptlet.
Apps Script documentation - force printing scriptlets
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.
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)