Loop For User Input and Adding summation of Dice Rolls - javascript

I am trying to make a game with JavaScript but I am stuck. I cannot figure out how to take the rolls from the dice and put it into a table to count how many rolls were made before the player runs out of money, and the other 3 requirements at the end of the rules::::: any advice would be super helpful!
The rules
As long as there is money, play the game.
Each round, the program rolls a virtual pair of dice for the user.
If the sum of the 2 dice is equal to 7, the player wins $4
otherwise, the player loses $1.
The program asks the user how many dollars they have to bet.
If the starting bet is less than or equal to 0, display an error message.
When the user clicks the Play button, the program then rolls the dice repeatedly until all the money is gone.
Hint: Use a loop construct to keep playing until the money is gone.
Hint: We created a rollDice() function in the Rolling Dice exercise.
The program keeps track of how many rolls were taken before the money ran out.
The program keeps track of the maximum amount of money held by the player.
The program keeps track of how many rolls were taken at the point when the user held the most money.
I couldn't get my code to paste properly so I've added a snippet.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title> Lucky Sevens </title>
<style>
</style>
<script>
<!--reset form field to natural state-->
function clearErrors() {
for (var loopCounter = 0;
loopCounter < document.forms["bet"].elements.length;
loopCounter++) {
if (document.forms["bet"].elements[loopCounter]
.parentElement.className.indexOf("has-") != -1) {
document.forms["bet"].elements[loopCounter]
.parentElement.className = "form-group";
}
}
}
<!--clear form fields-->
function resetForm() {
clearErrors();
document.forms["bet"]["num1"].value = "";
document.getElementById("results").style.display = "none";
document.getElementById("submitButton").innerText = "Submit";
document.forms["bet"]["num1"].focus();
alert("You have reset the form and will lose all progress.");
}
<!--verify user input is expected-->
function validateItems() {
clearErrors();
var num1 = document.forms["bet"]["num1"].value;
if (num1 == "" || isNaN(num1)) {
alert("Num1 must be filled in with a number.");
document.forms["bet"]["num1"]
.parentElement.className = "form-group has-error";
document.forms["bet"]["num1"].focus();
return false;
}
if (num1 >= 11) {
alert("Bet must be between $1-$10");
document.forms["bet"]["num1"]
.parentElement.className = "form-group has-error"
document.forms["bet"]["num1"].focus();
return false;
}
if (num1 <= 0) {
alert("Bet must be between $1-$10");
document.forms["bet"]["num1"]
.parentElement.className = "form-group has-error"
document.forms["bet"]["num1"].focus();
return false;
}
document.getElementById("results").style.display = "block";
document.getElementById("submitButton").innerText = "Roll Again";
document.getElementById("startingBet").innerText = num1;
return false;
}
function rollDice() {
var die1 = document.getElementById("die1");
var die2 = document.getElementById("die2");
var status = document.getElementById("status");
var d1=Math.floor(Math.random() * 6) + 1;
var d2=Math.floor(Math.random() * 6) + 1;
var diceTotal = d1 + d2;
die1.innerHTML = d1;
die2.innerHTML = d2;
status.innerHTML = "You rolled " + diceTotal + ".";
if(diceTotal == 7) {
status.innerHTML += " You win $4!";
}
if(diceTotal != 7){
status.innerHTML += " You lose $1.";
}
}
</script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
rel="stylesheet" type="text/css" />
</head>
<body>
<div class="container">
<h1>Lucky Sevens</h1>
<form name="bet" onsubmit="return validateItems();"
onreset="resetForm();" class="form-inline">
<div class="form-group">
<label for="num1">Starting Bet</label>
<input type="number" class="form-control" id="num1">
</div>
<button type="submit" onclick="rollDice()" id="submitButton" class="btn btn-default">Submit</button>
</form>
<h2 id="status" style="clear:left;"></h2>
<div id="die1" class="dice">0</div>
<div id="die2" class="dice">0</div>
<hr />
<table id="results" class="table table-striped" style="display:none;">
<tbody>
<tr>
<td>Starting Bet</td>
<td><span id="startingBet"></span></td>
</tr>
<tr>
<td>Total Rolls Before Going Broke</td>
</tr>
<tr>
<td>Highest Amount Won</td>
</tr>
<tr>
<td>Roll Count at Highest Amount Win</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>

Related

How to display different output based on a text box input using Javascript?

I am creating a grading system with a perfect score of 100. The total is automatically calculated depending the score provided and it is read only. Now, I want to show another text box a short remarks based on the total without the submit button. For example, if the grade is 90 and below, the remarks should automatically be set to 'Very Good' and if less than or equal to 80, the remarks will be "Good".
function findTotal(){
var arr = document.getElementsByName('qty');
var tot=0;
for(var i=0;i<arr.length;i++){
if(parseInt(arr[i].value))
tot += parseInt(arr[i].value);
}
document.getElementById('total').value = tot;
}
function calculate() {
var feedback = document.getElementById("total").value;
var greeting;
if (feedback >= 90) {
greeting = "OUTSTANDING";
} else if (feedback >= 80) {
greeting = "VERY GOOD";
} else if (feedback >= 70) {
greeting = "GOOD";
} else {
greeting = "Needs Improvement";
}
document.getElementById("feedback").value = greeting;
}
<div class="column3 tworow" style="background-color:#bbb;" align="center">
<table id="t01">
<tr>
<td>SCORE: <input type="text" name="total" id="total" style="text-align:center;font-size:20px" onkeyup="calculate()" readonly></td>
</tr>
<tr>
<td>FEEDBACK: <input type="text" name="feedback" id="feedback" style="text-align:center;font-size:20px" readonly></td>
</tr>
</table>
</div>
I tried to use different if/else statement with JavaScript but it is not picking up the elseif function.
Your code needed a lot of cleaning, there were for example 2 <th> nested tags I don't know why, here is a working flexible example, just insert the number and press calculate
function calculate() {
var feedback = document.getElementById("total").value;
var greeting;
if (feedback >= 90) {
greeting = "OUTSTANDING";
} else if (feedback >= 80) {
greeting = "VERY GOOD";
} else if (feedback >= 70) {
greeting = "GOOD";
} else {
greeting = "Needs Improvement";
}
document.getElementById("feedback").value = greeting;
}
<table class="column3 tworow" style="background-color:#bbb;" align="center">
<tr>
<th>TOTAL: <input type="text" name="total" id="total" style="text-align:center;font-size:20px"></th>
</tr>
<tr>
<th>FEEDBACK: <input type="text" name="feedback" id="feedback" style="text-align:center;font-size:20px"
readonly></th>
</th>
</tr>
</table>
<br>
<button onclick="calculate()">Calculate</button>
Also there were a lot of javascript errors, as noted by #Snel23
If you want to remove the Calculate button and make the feedback show whenever you insert something in the input field, just do this:
Remove the <button> tag
Add your <input onkeyup="calculate()"> to the <input> tag
Here is a snippet for that:
function calculate() {
var feedback = document.getElementById("total").value;
var greeting;
if (feedback >= 90) {
greeting = "OUTSTANDING";
} else if (feedback >= 80) {
greeting = "VERY GOOD";
} else if (feedback >= 70) {
greeting = "GOOD";
} else {
greeting = "Needs Improvement";
}
document.getElementById("feedback").value = greeting;
}
<table class="column3 tworow" style="background-color:#bbb;" align="center">
<tr>
<th>TOTAL: <input type="text" name="total" id="total" style="text-align:center;font-size:20px" onkeyup="calculate()"></th>
</tr>
<tr>
<th>FEEDBACK: <input type="text" name="feedback" id="feedback" style="text-align:center;font-size:20px"
readonly></th>
</th>
</tr>
</table>
First of all, in your if else statements, you started by comparing feedback but changed to time. Secondly, you were trying to insert html into an element that didn't exist, rather than set the value on <input id="feedback">
Finally, you were trying to set that value to text which is a variable that doesn't exist.
The below JS code should fix your issues:
var feedback = document.getElementById("total").value;
if (feedback >= 90) {
greeting = "OUTSTANDING";
} else if (feedback >=80) {
greeting = "VERY GOOD";
} else if (feedback >=70) {
greeting = "GOOD";
} else {
greeting = "Needs Improvement";
}
document.getElementById("feedback").value = greeting;

Limit the amount of times a button is clicked

for my college project im trying to limit the amount of times one of my buttons is being clicked to 3 times, I've been looking everywhere for code to do it and found some yesterday, it does give me alert when I've it the max amount of clicks but the function continues and im not sure why, here is the code I've been using.
var total = 0
var hitnumber = 0
var username = prompt("Enter username", "Player 1")
var compscore = 18
var card_1 = 0
var card_2 = 0
var ClickCount = 0
function NumberGen() {
hitnumber = Math.floor((Math.random() * 2) + 1);
document.getElementById("Random Number").innerHTML = username + " has
drawn " + hitnumber;
}
function Total_Number() {
total = total + hitnumber + card_1 + card_2;
document.getElementById("Total").innerHTML = username + " has a total
of " + total;
if(total >21){
window.location="../End_Game/End_Lose_Bust.html";
}
}
function Random_Number() {
card_1 = Math.floor((Math.random() * 2) + 1);
card_2 = Math.floor((Math.random() * 2) + 1);
document.getElementById("Stcards").innerHTML = username + " has drawn "
+ card_1 + " and " + card_2 + " as their first cards.";
}
function menuButton(button) {
switch(button)
{
case "Stick":
if (total > 21) {
window.location="../End_Game/End_Lose_Bust.html";
} else if (total == 21){
window.location="../End_Game/End_Win_21.html";
} else if (total > compscore) {
window.location="../End_Game/End_Win.html";
} else if (total == compscore) {
window.location="../End_Game/End_Draw.html";
} else {
window.location="../End_Game/End_lose.html";
}
}
}
function Hidebutton() {
document.getElementById("Hit").style.visibility = 'visible';
document.getElementById("Stick").style.visibility = 'visible';
document.getElementById("Deal").style.visibility = 'hidden';
}
function countClicks() {
var clickLimit = 3;
if(ClickCount>=clickLimit) {
alert("You have drawn the max amount of crads");
return false;
}
else
{
ClickCount++;
return true;
}
}
HTML
<!doctype html>
<html>
<head>
<title>Pontoon Game</title>
<link rel="stylesheet" type="text/css" href="Main_Game.css">
</head>
<body>
<h1>Pontoon</h1>
<div id="Control">
<input type="button" id="Hit" onclick="NumberGen(); Total_Number(); countClicks()" value="Hit" style="visibility: hidden" />
<input type="button" id="Stick" onclick="menuButton(value)" style="visibility: hidden" value="Stick" />
<input type="button" id="Deal" onclick="Hidebutton(); Random_Number()" value="Deal" />
</div>
<div class="RNG">
<p id="Stcards"></p>
<p id="Random Number"></p>
<p id="Total"></p>
</div>
<div class="Rules">
<p>
Welcome to Pontoon, the goal of the game is to make your cards reach a combined value of 21 before the dealer (computer). during the game you will have two clickable buttons, these are hit and stick.
</p>
<p>
>Hit - This button allows you to collect another card.
</p>
<p>
>Stick - This buttom allows you to stay at the value of cards you have, you should only use this button at the end of the game when you feel you cannot get any closer to 21 without going bust.
</p>
<p>
Going bust means you have gone over 21, when this happens the game will automaticly end as you have gone bust.
</p>
</div>
</body>
</html>
Cheers in advance.
You are calling countClicks at the end of onclick. Change it to this:
if (countClicks()) { NumberGen(); Total_Number();}
Try this
var count = 0;
function myfns(){
count++;
console.log(count);
if (count>3){
document.getElementById("btn").disabled = true;
alert("You can only click this button 3 times !!!");
}
}
<button id="btn" onclick="myfns()">Click Me</button>
I have edited your code also following is your code
var total = 0
var hitnumber = 0
var username = prompt("Enter username", "Player 1")
var compscore = 18
var card_1 = 0
var card_2 = 0
var ClickCount = 0
function NumberGen() {
hitnumber = Math.floor((Math.random() * 2) + 1);
document.getElementById("Random Number").innerHTML = username + " has drawn " + hitnumber;
}
function Total_Number() {
total = total + hitnumber + card_1 + card_2;
document.getElementById("Total").innerHTML = username + " has a total of " + total;
if (total > 21) {
window.location = "../End_Game/End_Lose_Bust.html";
}
}
function Random_Number() {
card_1 = Math.floor((Math.random() * 2) + 1);
card_2 = Math.floor((Math.random() * 2) + 1);
document.getElementById("Stcards").innerHTML = username + " has drawn " +
card_1 + " and " + card_2 + " as their first cards.";
}
function menuButton(button) {
switch (button)
{
case "Stick":
if (total > 21) {
window.location = "../End_Game/End_Lose_Bust.html";
} else if (total == 21) {
window.location = "../End_Game/End_Win_21.html";
} else if (total > compscore) {
window.location = "../End_Game/End_Win.html";
} else if (total == compscore) {
window.location = "../End_Game/End_Draw.html";
} else {
window.location = "../End_Game/End_lose.html";
}
}
}
function Hidebutton() {
document.getElementById("Hit").style.visibility = 'visible';
document.getElementById("Stick").style.visibility = 'visible';
document.getElementById("Deal").style.visibility = 'hidden';
}
function countClicks() {
var clickLimit = 3;
if (ClickCount >= clickLimit) {
alert("You have drawn the max amount of crads");
return false;
} else {
NumberGen();
Total_Number();
ClickCount++;
return true;
}
}
<html>
<head>
<title>Pontoon Game</title>
<link rel="stylesheet" type="text/css" href="Main_Game.css">
</head>
<body>
<h1>Pontoon</h1>
<div id="Control">
<input type="button" id="Hit" onclick=" countClicks()" value="Hit" style="visibility: hidden" />
<input type="button" id="Stick" onclick="menuButton(value)" style="visibility: hidden" value="Stick" />
<input type="button" id="Deal" onclick="Hidebutton(); Random_Number()" value="Deal" />
</div>
<div class="RNG">
<p id="Stcards"></p>
<p id="Random Number"></p>
<p id="Total"></p>
</div>
<div class="Rules">
<p>
Welcome to Pontoon, the goal of the game is to make your cards reach a combined value of 21 before the dealer (computer). during the game you will have two clickable buttons, these are hit and stick.
</p>
<p>
>Hit - This button allows you to collect another card.
</p>
<p>
>Stick - This buttom allows you to stay at the value of cards you have, you should only use this button at the end of the game when you feel you cannot get any closer to 21 without going bust.
</p>
<p>
Going bust means you have gone over 21, when this happens the game will automaticly end as you have gone bust.
</p>
</div>
</body>
</html>

Adding JavaScript calculation function to HTML form

I am trying to link a basic calculation in an external JavaScript
The form is pretty simple and the function just checks to make sure the step number is even. I have reviewed the code many times, but when I enter the numbers and hit submit nothing happens. Any suggestions? Its seems like I just don't have the function and input elements linked correctly.
here is the code:
function evenNumbers() {
var evenNumberBtn = document.querySelector("button");
evenNumberBtn.addEventListener("click", evenNumbers);
var startNumber = parseInt(document.getElementById("startNumber").value);
var endNumber = parseInt(document.getElementById("endNumber").value);
var stepNumber = parseInt(document.getElementById("stepNumber").value);
while (startNumber + stepNumber <= endNumber) {
if (startNumber <= endNumber){
if (startNumber % 2 === 0 && stepNumber % 2 === 0) {
startNumber += stepNumber;
alert(startNumber);
} else if (startNumber % 2 !== 0 && stepNumber % 2 === 0) {
startNumber += 1 + (stepNumber);
alert(startNumber);
} else {
alert("Please enter a positive number for the step value.");
}
} else {
alert("Please enter an ending number greater than the start number.");
}
}
}
<!DOCTYPE html>
<html>
<head>
<title>HTML5, CSS3 and JavaScript demo</title>
</head>
<body>
<form>
<label>Start: </label>
<input type="number" id="startNumber"/><br/>
<label>End: </label>
<input type="number" id="endNumber"/><br/>
<label>Step by:</label>
<input type="number" id="stepNumber"/><br/>
<button onclick="evenNumbers();">Submit</button>
<p></p>
</form>
<!-- End your code here -->
</body>
</html>
Try this:
In .js file
var evenNumberBtn = document.querySelector("button");
evenNumberBtn.addEventListener("click", evenNumbers);
I have removed your actual code for now, because it has some issues whereby you can end up in an infinite loop (I definitely did and it crashed Chrome 😊).
Your issue was in your HTML
Before
<button onclick("evenNumbers();")>Submit</button>
After
<button onclick="evenNumbers();">Submit</button>
function evenNumbers() {
var startNumber = parseInt(document.getElementById("startNumber").value);
var endNumber = parseInt(document.getElementById("endNumber").value);
var stepNumber = parseInt(document.getElementById("stepNumber").value);
alert(startNumber + ',' + endNumber + ',' + stepNumber);
}
<!DOCTYPE html>
<html>
<head>
<title>HTML5, CSS3 and JavaScript demo</title>
</head>
<body>
<form>
<label>Start: </label>
<input type="text" id="startNumber"/><br/>
<label>End: </label>
<input type="text" id="endNumber"/><br/>
<label>Step by:</label>
<input type="text" id="stepNumber"/><br/>
<button onclick="evenNumbers();">Submit</button>
<p></p>
</form>
<!-- End your code here -->
</body>
</html>
function evenNumbers() {
//var evenNumberBtn = document.querySelector("button");
//evenNumberBtn.addEventListener("click", evenNumbers);
var startNumber = parseInt(document.getElementById("startNumber").value);
var endNumber = parseInt(document.getElementById("endNumber").value);
var stepNumber = parseInt(document.getElementById("stepNumber").value);
while (startNumber + stepNumber <= endNumber) {
if (startNumber <= endNumber){
if (startNumber % 2 === 0 && stepNumber % 2 === 0) {
startNumber += stepNumber;
alert(startNumber);
} else if (startNumber % 2 !== 0 && stepNumber % 2 === 0) {
startNumber += 1 + (stepNumber);
alert(startNumber);
} else {
alert("Please enter a positive number for the step value.");
}
} else {
alert("Please enter an ending number greater than the start number.");
}
}
}
<!DOCTYPE html>
<html>
<head>
<title>HTML5, CSS3 and JavaScript demo</title>
</head>
<body>
<form>
<label>Start: </label>
<input type="text" id="startNumber"/><br/>
<label>End: </label>
<input type="text" id="endNumber"/><br/>
<label>Step by:</label>
<input type="text" id="stepNumber"/><br/>
<button onclick="evenNumbers()">Submit</button>
<p></p>
</form>
<!-- End your code here -->
</body>
</html>
The first two lines inside evenNumber function need to be outside the function, Otherwise your code never reaches inside that block.
$( document ).ready(function() {
var evenNumberBtn = document.querySelector("button");
evenNumberBtn.addEventListener("click", evenNumbers);
function evenNumbers() {
/*
your code here
*/
}
});
Also the logic inside the evenNumbers seems wrong. You might need to change that too.

display and calculate score for javascript quiz

i'm a teacher and have just started learning to code for making online quizzes for my students. I'm still very new to programming like JavaScript and php, and I've tried to looked for sources online to help create my quizzes. I have 2 questions:
1). I've set a timer for the quiz but everytime when the time is up, it just keeps counting, what should I put in the
if (parseInt(min) == 0) {
clearTimeout(tim);
location.href = "";
section to redirect my student to the result page or other pages?
(2) My quizzes are mostly fill-in-the-blanks questions and I wonder how to store the point of each question and then show the total score to my students at the end of the quiz? Many thanks!.
Here's my code:
<html>
<head>
<script language ="javascript" >
var tim;
var min = 0;
var sec = 30;
var f = new Date();
function f1() {
f2();
document.getElementById("starttime").innerHTML = "Your started your quiz at " + f.getHours() + ":" + f.getMinutes();
}
function f2() {
if (parseInt(sec) > 0) {
sec = parseInt(sec) - 1;
document.getElementById("showtime").innerHTML = "Your Left Time is :"+min+" Minutes ," + sec+" Seconds";
tim = setTimeout("f2()", 1000);
}
else {
if (parseInt(sec) == 0) {
min = parseInt(min) - 1;
if (parseInt(min) == 0) {
clearTimeout(tim);
location.href = "www.rawlanguages.com";
}
else {
sec = 60;
document.getElementById("showtime").innerHTML = "Your Left Time is :" + min + " Minutes ," + sec + " Seconds";
tim = setTimeout("f2()", 1000);
}
}
}
}
</script>
<title>Quiz</title>
<h1>P.1 Grammar Quiz</h1>
<body>
<div id="ques0" class="ques">
<h2>Question</h2>
<p>She
<input type="text" name="answer0"/> a girl.</p>
</div>
<div id="ques1" class="ques">
<h2>Question</h2>
<p>"is", "am" and "are" are</p>
<ul>
<li>
<input type="radio" name="answer1" value="Present tense" />
<label>Present tense</label>
</li>
<li>
<input type="radio" name="answer1" value="Past tense" />
<label>Past tense</label>
</li>
<li>
<input type="radio" name="answer1" value="Future tense" />
<label>Future tense</label>
</li>
</ul>
</div>
<div id="ques2" class="ques">
<h2>Question</h2>
<p>He
<input type="text" name="answer2"/> a policeman.
</p>
</div>
Check answer!
<script src="JQ.js"></script>
<script src="function.js"></script>
<body onload="f1()" >
<form id="form1" runat="server">
<div>
<table width="100%" align="center">
<tr>
<td colspan="2">
</td>
</tr>
<tr>
<td>
<div id="starttime"></div>
<div id="endtime"></div>
<div id="showtime"></div>
</td>
</tr>
<tr>
<td>
</td>
</tr>
</table>
</div>
</form>
</body>
</head>
</html>
Your code is good enough for a beginner but it requires some improvements.
<script type="text/javascript" >//language ="javascript" is obsolete
//var tim; //no need at all
//var min = 0; //no need at all
//var sec = 30; //there is better way
//var f = new Date(); //no need to be global
function f1(sec) {//define (declare) sec as parameter
f2(); //call the function
var f = new Date();
document.getElementById("starttime").innerHTML = "Your started your quiz at " + f.getHours() + ":" + f.getMinutes();
var showtime = document.getElementById("showtime"); //used many times
//Here we put (closure) f2
function f2() {
//f2 knows sec from parent scope
if (sec <= 0) {//parseInt(sec) no need. sec is int
showtime.innerHTML = 'Time is over';
//ShowAnswers(); //show on the same page or post to .php
return;
}
sec--;// = parseInt(sec) - 1;
showtime.innerHTML = "Your Left Time is :" + Math.floor(sec / 60) +" Minutes ," + (sec % 60) +" Seconds";
setTimeout(f2, 1000);//"f2()" is correct but this way is better
/* no need in remaining code
}
else {
if (parseInt(sec) == 0) {
min = parseInt(min) - 1;
if (parseInt(min) == 0) {
clearTimeout(tim);
location.href = "www.rawlanguages.com";
}
else {
sec = 60;
document.getElementById("showtime").innerHTML = "Your Left Time is :" + min + " Minutes ," + sec + " Seconds";
tim = setTimeout("f2()", 1000);
}
}
}
*/
}//f2
}//f1
</script>
<body onload="f1(90)"><!--Here we send seconds to the function -->
Also note that all your quiz starting from <h1>P.1... must be inside body container.

Javascript do-while looping problems

I need help with looping the javascript in a do/while statement loop.
The problems I am having is that I don't want to display the incorrect information in my table when entering an invalid product, but it does display in the document.write. I need help in order to make sure that the incorrect information won't be displayed.
Also, when I hit "ok" to add more to my order, it doesn't loop it but merely displays the document.write. I want it to loop if you hit the "ok" button.
Thank you for the help.
Here is the code:
<html>
<head><title>Javascript Assignment 3: Daniel Weiner</title>
</head>
<body bgcolor="brown">
<h1 align="center">Big Ben's Burgers-eCommerce</h1>
<table border="1" width="100%" height="450px" bgcolor="gray"><tr>
<th align="center">Product/Service</th>
<th align="center">Price</th>
<th align="center">Discount</th>
</tr>
<tr bgcolor="orange">
<td align="center"><font size="3">Hamburger
<br>
<br>
Classic Hamburger
<td align="right" bgcolor="orange"><font size="3">$8.00</font></td>
<td align="center" bgcolor="orange"><font size="3">.10</font></td>
</tr>
<tr bgcolor="orange">
<td align="center"><font size="3">Cheeseburger
<br>
<br>
Classic Cheeseburger
</font></td>
<td align="right" bgcolor="orange"><font size="3">$9.00</font></td>
<td align="center" bgcolor="orange"><font size="3">.05</font></td>
</tr>
<tr bgcolor="orange">
<td align="center"><font size="3">Soda
<br>
<br>
Fabulous Drinks
</font></td>
<td align="right" bgcolor="orange"><font size="3">$2.00
</font></td>
<td align="center" bgcolor="orange"><font size="3"> .07</font></td>
</tr>
<tr bgcolor="red">
<td align="center"><font size="3"> French Fries
<br>
<br>
Fries
</font></td>
<td align="right" bgcolor="red"><font size="3"> $4.00</font></td>
<td align="center" bgcolor="red"><font size="3">.15</font></td>
</table>
<script type="text/javascript">
/*Daniel Weiner, Fengpeng Yuan, Javascript 2, Nov 4,2011*/
var username;
var bprice= 8;
var chprice= 9;
var sprice= 2;
var fprice= 4;
var price= 0;
var a;
var b;
var product= "hamburger, cheeseburger, soda, fries";
var quantity =0;
var total;
var cost = 0;
var discount= 0;
do{
username =prompt("Welcome to Big Ben's Burgers. Please enter your name.", "");
alert("Hello " + username+". Please look through our available products and services before placing your order.","");
product=prompt("What do you want?","");
quantity =1*prompt("How many of " +product+ " would you like?");
if (product == "hamburger")
{
price = bprice;
discount = .1;
}
else if (product == "cheeseburger")
{
price = chprice;
discount = .05;
}
else if (product == "soda")
{
price = sprice;
discount = .07;
}
else if (product == "fries")
{
price = fprice;
discount = .15;
}
else{
alert("Sorry, " +username+ " Your item not found.");
}
cost=price*quantity
discount=price*discount*quantity
total=cost-discount
document.write("The cost of buying " +quantity+ " of " +product+ " is $" +cost+ ".<br/>");
document.write("This discount for this purchase is $" +discount+ ".<br/>");
}while(a==false)
a = confirm("Do you want to place another order?");
(b==false)
document.write("Thank you for placing an order with us, " +username+ ".<br/>");
document.write("The total order cost is $" +total+ ".");
</script>
</body>
</html>
for the second part of the question, you have to use the statement bellow in the loop
a = confirm("Do you want to place another order?");
You're re-iterating the loop if the user hits cancel. Change while(a==false) to while(a==true) or simply while(a)
Also put the line
a = confirm("Do you want to place another order?");
as the last line in your loop, instead of the line after.
You can set a flag var that lets you know if the item was found or not and check it at the end of your loop to avoid displaying data for non-existing items:
<script type="text/javascript">
/*Daniel Weiner, Fengpeng Yuan, Javascript 2, Nov 4,2011*/
var username;
var bprice= 8;
var chprice= 9;
var sprice= 2;
var fprice= 4;
var price= 0;
var a;
var b;
var product= "hamburger, cheeseburger, soda, fries";
var quantity =0;
var total;
var cost = 0;
var discount= 0;
var flag;
do{
flag = true; //assume found unless otherwise
username =prompt("Welcome to Big Ben's Burgers. Please enter your name.", "");
alert("Hello " + username+". Please look through our available products and services before placing your order.","");
product=prompt("What do you want?","");
quantity =1*prompt("How many of " +product+ " would you like?");
if (product == "hamburger")
{
price = bprice;
discount = .1;
}
else if (product == "cheeseburger")
{
price = chprice;
discount = .05;
}
else if (product == "soda")
{
price = sprice;
discount = .07;
}
else if (product == "fries")
{
price = fprice;
discount = .15;
}
else{
alert("Sorry, " +username+ " Your item not found.");
flag = false;
}
if(flag){
cost=price*quantity
discount=price*discount*quantity
total=cost-discount
document.write("The cost of buying " +quantity+ " of " +product+ " is $" +cost+ ".<br/>");
document.write("This discount for this purchase is $" +discount+ ".<br/>");
}
a = confirm("Do you want to place another order?");
}while(a);
alert('goodbye');
</script>
It looks like you aren't conditioning the part that outputs the result on whether or not a valid product was selected. You need something like the following;
do{
....
productValid = false;
if (product == "hamburger")
{
price = bprice;
discount = .1;
productValid = true;
}
else if (product == "cheeseburger")
{
price = chprice;
discount = .05;
productValid = true;
}
else if (product == "soda")
{
price = sprice;
discount = .07;
productValid = true;
}
else if (product == "fries")
{
price = fprice;
discount = .15;
productValid = true;
}
else{
alert("Sorry, " +username+ " Your item not found.");
}
if(productValid){
cost=price*quantity
discount=price*discount*quantity
total=cost-discount
document.write("The cost of buying " +quantity+ " of " +product+ " is $" +cost+ ".<br/>");
document.write("This discount for this purchase is $" +discount+ ".<br/>");
}
else
{
document.write("No valid product selected<br>");
}
a = confirm("Do you want to place another order?");
}while(a==true)

Categories

Resources