My program needs to consist of a for loop, use both input functions already created ( name and number) and totals need to be acquired. I also need to be able to CANCEL and go to my doc.write where i would input name and number. I also need to give the user another chance to type in their name or number if they accidentally typed in number where letters should be and vise-versa. I think i have majority of the structure right, any help would be greatly appreciated!
function inputName() {
var nameIn = prompt("Enter your Name");
while(!isNaN(nameIn)) {
nameIn = prompt("Must contain only letters");
}
return nameIn;
}
/* INPUT NUMBER */
function inputNum(){
var numIn=parseFloat(prompt("Enter the number of hours worked \n 0-60 hours"));
var min=0;
var max=60;
while(numIn>min && numIn>max ){
numIn=prompt("Enter a valid number between 0-60");
return numIn;
}
</script>
<body>
<script type="text/javascript">
//DECLARATIONS
var wage=10.00;
var earned; // hrsWrked*wage
var totHrsWrked=0;
var totEarning=0;
var BR= "
";
var howMany;
var loopControl;
//INPUT & PROCESSING
howMany=parseFloat(prompt("How many employees are you inputing?"));
for(loopControl=1 ; loopControl <= howMany; ++loopControl){
var inpNam=inputName();
var inpNumber=inputNum();
earned= inpNumber*wage;
totEarning+=earned;
totHrsWrked+=inpNumber;
//OUTPUT
document.write("Name: "+ inpNam+ BR);
document.write("Hours Worked: " + inpNumber + BR);
document.write("Money Earned: $ " + earned + BR +BR);
}
document.write("Total Hours Worked: " + totHrsWrked.toFixed(2) + BR);
document.write("Total Earnings: " + "$"+totEarning.toFixed(2)+ BR+BR);
</script>
</body>
</html>
Here's the edited version of your code. :)
<! doctype html>
<html>
<body>
<script>
//DECLARATIONS
var wage=10.00, earned, totHrsWrked=0, totEarning=0, howMany;
//INPUT & PROCESSING
howMany=parseFloat(prompt("No of employees"));
for( var loopControl=1 ; loopControl <= howMany; ++loopControl)
{
var inpNam=inputName();
var inpNumber=inputNum();
earned= inpNumber*wage;
totEarning+= (+earned);
totHrsWrked+= (+inpNumber);
//OUTPUT
document.write("Name: "+ inpNam+ "<br>");
document.write("\n Hours Worked: " + inpNumber + "<br>");
document.write("Money Earned: $ " + earned + "<br><br>");
}
document.write("Total Hours Worked: " + totHrsWrked.toFixed(2)+ "<br>");
document.write("Total Earnings: " + "$"+totEarning.toFixed(2)+ "<br>");
//INPUT NAME
function inputName() {
var nameIn = prompt("Enter your Name");
while(!isNaN(nameIn)) {
nameIn = prompt("Must contain only letters");
}
return nameIn;
}
//INPUT NUMBER
function inputNum(){
var numIn=parseFloat(prompt("Enter the number of hours worked \n 0-60 hours"));
var min=0;
var max=60;
while(numIn<=min || numIn>=max ){
numIn=prompt("Enter a valid number between 0-60");
}
return numIn;
}
</script>
</body>
</html>
Related
So I'm currently taking a coding class and am not very well versed in coding. I'm having trouble with a getelementbyid block which isn't writing my looped array for an assignment. Could anyone help me out?
Here's the code:
<html>
<head>
<title>
Looping Assignment
</title>
</head>
<body>
<h1 align=center>Name and Grades</h1>
<p id="message"> Name </p>
<p id="message2"> Grade </p>
<script>
var input = []
var message = " "
var message2 = " "
var n = 0
var i = 1
var names = n
var grade = i
for (n = 0; n < 1; n++) {
var names = n + 1
input[n] = window.prompt("Enter First Name" + names)
message += "Your name is " + input[n] + "<br>"
}
for (i = 1; i < 5; i++) {
input[i] = window.prompt("Enter Grade (numerical value)" + grade)
message2 += "Grade " + i + " is " + input[i] + "<br>"
}
document.getElementById(message).innerHTML = "your name is " + input[n] + "<br>"
document.getElementById(message2).innerHTML = "Grade" + i + " is " + input[i] + "<br"
</script>
</body>
</html>
Your variables and your id-s have the same names. By doing getElementbyId(message) you are passing the variables' values instead of the fixed id you gave to your elements.
You need to put the id-s in quotes as follows:
document.getElementById("message")
document.getElementById("message2")
Tested at my end and this is working code
<!DOCTYPE html>
<html>
<head>
<title>
Looping Assignment
</title>
</head>
<body>
<h1 align=center>Name and Grades</h1>
<p id="message"> Name </p>
<p id="message2"> Grade </p>
<script>
var input = []
var message = " "
var message2 = " "
var n = 0
var i = 1
var names = n
var grade = i
for (n = 0; n < 1; n++) {
var names = n + 1
input[n] = window.prompt("Enter First Name" + names)
message += "Your name is " + input[n] + "<br>"
}
for (i = 1; i < 5; i++) {
input[i] = window.prompt("Enter Grade (numerical value)" + grade)
message2 += "Grade " + i + " is " + input[i] + "<br>"
}
document.getElementById('message').innerHTML = "your name is " + input[n] + "<br>"
document.getElementById('message2').innerHTML = "Grade" + i + " is " + input[i] + "<br"
</script>
</body>
</html>
error:-
The id of getElementbyId must be in quotes
Make sure your selectors are strings
document.getElementById("message"); not document.getElementById(message);
Make sure you end your lines of code with semi-colons. This is not optional even though the code will attempt to run without them.
Change your output to render your accumulated data - right now you're overwriting your output every time you loop.
Note: I don't know what you're doing with the numerical value inside of the prompt methods (names and grade ) so I didn't touch it.
Example:
<!DOCTYPE html>
<html>
<head>
<title>
Looping Assignment
</title>
</head>
<body>
<h1 align=center>Name and Grades</h1>
<p id="message"> Name </p>
<p id="message2"> Grade </p>
<script>
var input = [];
var message = " ";
var message2 = " ";
var n = 0;
var i = 1;
var names = n;
var grade = i;
for (n = 0; n < 1; n++) {
var names = n + 1
input[n] = window.prompt("Enter First Name " + names)
message += "Your name is " + input[n] + "<br>";
}
for (i = 1; i < 5; i++) {
input[i] = window.prompt("Enter Grade (numerical value) " + grade)
message2 += "Grade " + i + " is " + input[i] + "<br>";
}
document.getElementById("message").innerHTML = message + "<br>";
document.getElementById("message2").innerHTML = message2 + "<br>";
</script>
#SlavicMilk
Below should be sufficient for your assignment:
HTML (index.html):
<h1 style="text-align: center">Name and Grades</h1>
<table>
<thead>
<th>Name</th>
<th>Grade</th>
</thead>
<tbody id="data">
</tbody>
</table>
<script src="script.js"></script>
JS (script.js):
let student = []
for (let i = 0; i < 5; i++) {
student[i] = {
"name": window.prompt(`Enter Name ${i + 1}`),
"grade": window.prompt(`Enter Grade (numerical value) ${i + 1}`)
}
}
document.getElementById('data').innerHTML = student.map(student => {
return `<tr><td>${student.name}</td><td>${student.grade}</td></tr>`
})
I wanna add an if/else statement that prints "Only Number are accepted", for older browsers, where they allow you to add a string in a input with type=number.
var bttn = document.getElementById("agebttn");
bttn.addEventListener("click", bttnClicked);
function calculate(startingYear) {
var dateObj = new Date()
var currentYear = dateObj.getFullYear()
return currentYear - startingYear;
}
function bttnClicked() {
console.log("bttn clicked");
var age = parseInt(document.getElementById('age').value);
var yearsAlive = calculate(age);
var html = "You entered " + age;
html += "<br />You have been alive for " + yearsAlive + " years";
document.getElementById('answer').innerHTML = html;
}
<body>
<h1>Age Calculator</h1>
<input type="number" id="age" placeholder="Enter your birthyear">
<input type="button" id="agebttn" value="Calc" />
<div id="answer">
</div>
</body>
You can check if you were able to parse int or not using isNaN function here:
function bttnClicked() {
console.log("bttn clicked");
var age = parseInt(document.getElementById('age').value);
if(isNaN(age)){
document.getElementById('answer').innerHTML = "<b>Only Numbers Accepted</b>";
return;
}
var yearsAlive = calculate(age);
var html = "You entered " + age;
html += "<br />You have been alive for " + yearsAlive + " years";
document.getElementById('answer').innerHTML = html;
}
CMIIW
from what i see , you want to print that result from your script logic into your
div tag with ID = answer right? and you want to get only number input?
you would want to use !isNan(age) function to validate your input so when they validate and got not a number input , it will throw you back error message on your else condition
Been browsing SO for some time since I picked up a programming course, and have found it to be an awesome community and great place for knowledge.
Currently I'm stuck with a JavaScript function that I'm trying to clean up.
I need to have names input into an array, and then when I run a 'start' function, it would display the amount of names as a number, and then show each name on a new line.
I've managed to get it working, however there is a ',' character at the start of each line. I've tried various ways to get around it (using replace and split + join) but had no luck so far.
var arrName = [];
var custName;
function start(){
var totalName = 0;
var count = 0;
document.getElementById("output").innerHTML = " ";
while(count < arrName.length){
totalName++;
count++;
};
document.getElementById("output").innerHTML = "The total names in the array are: " + totalName + "<br />" + arrName;
}
function addName(){
custName = document.getElementById("custname").value;
if(!custName){
alert("Empty Name!");
}
else{
arrName.push(custName + "<br>");
return custName;}
}
The reason is most likely because you are trying to display arrName which is an Array with this code: document.getElementById("output").innerHTML = "The total names in the array are: " + totalName + "<br />" + arrName;
Here's what I'd suggest:
var arrName = [];
var custName;
function start(){
var totalName = 0;
var count = 0;
document.getElementById("output").innerHTML = " ";
while(count < arrName.length){
totalName++;
count++;
}
var strOutput = "The total names in the array are: ";
strOutput += totalName + "<br />" + arrName.join("<br />");
document.getElementById("output").innerHTML = " ";
document.getElementById("output").innerHTML = strOutput;
}
function addName(){
custName = document.getElementById("custname").value;
if(!custName){
alert("Empty Name!");
}
else{
arrName.push(custName);
return custName;}
}
Since there is no need for the WHILE Loop, You can skip it like so:
var arrName = [];
var custName;
function start(){
var totalName = arrName.length;
var strOutput = "The total names in the array are: ";
strOutput += totalName + "<br />" + arrName.join("<br />");
document.getElementById("output").innerHTML = " ";
document.getElementById("output").innerHTML = strOutput;
}
function addName(){
custName = document.getElementById("custname").value;
if(!custName){
alert("Empty Name!");
}
else{
arrName.push(custName);
return custName;
}
}
An array when console logged or inserted to DOM directly will be represented as item1,item2,item3,item4
So simply, arrName.join("<br />")
Also, your while loop can be simply replaced by
totalName = arrName.length;
count = arrName.length
I'm receiving NotANumber for my total from movieTotal, as well as im not getting the correct value of adding pricePerTicket + pricePerDinner. Can someone help me figure out what im doing wrong?
<script type="text/javascript">
<!--
var ticket, earlyBirdTicket, WeekDinner, weekendDinner, numberOfTickets, TotalDue;
var numberOfTickets, pricePerTicket, pricePerDinner, costOfDandT, totalAmountOwed;
var totalDandT, yes, week, movieTotal;
var ticket = 5;
var nightTicket = 10;
var weekDinner = 8;
var weekendDinner = 12;
var yes = ticket;
var week = weekDinner;
var movieTotal = totalDandT * numberOfTickets;
totalDandT = pricePerDinner + pricePerTicket;
numberOfTickets = prompt ("How many tickets?");
pricePerTicket = prompt ("Is this earlybird? yes/no ");
pricePerDinner = prompt ("weekend or weekday? week/weekend ");
pricePerTicket = parseInt(pricePerTicket);
pricePerDinner = parseInt(pricePerDinner);
movieTotal = parseInt (movieTotal);
if (pricePerTicket = yes)
{
pricePerTicket = ticket;
}
else
{
pricePerTicket = nightTicket;
}
if (pricePerDinner = week)
{
pricePerDinner = weekDinner;
}
else
{
pricePerDinner = weekendDinner;
}
document.write ("<br>Number of tickets sold : " + numberOfTickets);
document.write ("<br>Cost per ticket tonight : $" + pricePerTicket);
document.write ("<br>Cost per dinner tonight : $" + pricePerDinner);
document.write ("<br>Cost of dinner and ticket : $" + pricePerTicket + pricePerDinner);
document.write ("<br> Your total today is $" + movieTotal);
// -->
</script>
You have not initialized the variables. You should do it before using them.
Uninitialized variables are equals to undefined so yes.undefined plus undefined is not a number.
I'm writing a script that parses an XML file and displays it in html. Here it is:
<script>
$.get("api.xml", function (xml) {
$(xml).find("row").each(function () {
var date = $(this).attr('date');
var amount = $(this).attr('amount');
var balance = $(this).attr('balance');
document.write("A: " + date + "<br />B: " + amount + " ISK<br />C: " + balance + " ISK<br /><br /><br /><br />");
});
});
</script>
I want to modify the output of "document.write", so that if the value "amount" is positive, enter the word "green", otherwise, if negative, enter the word "red". I tried to write it as follows:
<script>
$.get("api.xml", function (xml) {
$(xml).find("row").each(function () {
var date = $(this).attr('date');
var amount = $(this).attr('amount');
var balance = $(this).attr('balance');
document.write("<script> if (amount >= 0) { document.write("green"); } else{ document.write("red"); } </scri" + "pt>");
});
});
</script>
But in that piece, I get a syntax error in "document.write". What I have written wrong and how could fix it?
I think you can compute the color before writing the output with document.write.
Something like this should work:
<script>
$.get("api.xml", function (xml) {
$(xml).find("row").each(function () {
var date = $(this).attr('date');
var amount = $(this).attr('amount');
var balance = $(this).attr('balance');
var color = "green";
if (amount < 0) {
color = "red";
}
document.write("A: " + date + "<br />B: <span style='color:" + color + "'>" + amount + " ISK</span><br />C: " + balance + " ISK<br /><br /><br /><br />");
});
});
</script>
(syntax unchecked)
To get an answer just look, how this code is highlighted. The words 'green' and 'red' are outside the quotes. You should use single quotes (or escape the double quotes).
The other question is why do you use metaprogramming for such a simple task. Just write a condition with two different document.write statements.
<script>
$.get("api.xml", function (xml) {
$(xml).find("row").each(function () {
var date = $(this).attr('date');
var amount = $(this).attr('amount');
var balance = $(this).attr('balance');
document.write(amount >= 0 ? "green" : "red");
});
});
</script>