Difficulty assigning a Discount - javascript

As the title says, I'm having trouble assigning discounts to my products. When I load the page it says nan and undefined. Any help is appreciated. Thankyou!
This is my JavaScript code:
var ProductType;
var ProductQty;
var ProductPrice;
var DiscountPercent;
var TotalAmount;
function calculate() {
ProductType = prompt("Please enter the type of product you require!").toUpperCase();
document.write("<br>");
ProductQty = prompt("Please enter the number of products you require!");
elsestatement();
ProductQty = parseInt(ProductQty);
document.write("Type of Products:" + ProductType);
document.write("<br>");
document.write("Number of Products:" + ProductQty);
document.write("<br>");
var GrossAmount =(ProductPrice) * (ProductQty);
document.write("Gross Amount is:" + GrossAmount);
GrossAmount = parseInt(GrossAmount);
discountAmt();
var DiscountAmount = (GrossAmount) - (GrossAmount) * (DiscountPercent)
var TotalAmount = (GrossAmount) * (DiscountPercent)
document.write("<br>");
document.write("Discount Amount:" + DiscountAmount)
document.write("<br>");
document.write("Discount Percent:" + DiscountPercent)
document.write("<br>");
document.write("Total Amount:" + TotalAmount)
}
function elsestatement(){
if (ProductType == 'A') {
ProductPrice = 100;
} else if (ProductType == 'B') {
ProductPrice = 75;
} else if (ProductType == 'C'){
ProductPrice = 50;
}
else {
document.write("<br>");
document.write("Invalid Product Type");
document.write("<br>");
}
if (ProductQty <1|| ProductQty >100) {
document.write("Invalid Quantity")
}
}
function discountAmt() {
if (GrossAmount <200) {
DiscountPercent = '0';
} else if (GrossAmount >= 200 && GrossAmount<=399.99) {
DiscountPercent = '.05';
} else if (GrossAmount>=400 && GrossAmount<=599.99 ) {
DiscountPercent = '.075';
} else if (GrossAmount >=600)
DiscountPercent = '.1';
}
This is my HTML Code:
<!DOCTYPE html>
<html>
<title>Product</title>
<body>
<h1>Product Calc</h1>
<script src="Product.js"> </script>
<script>calculate()</script>
<script>elsestatement()</script>
<script>discountAmt()</script>
</body>

Sorry for the confusion. I was mistaken about the unclosed function. Instead, the problem is that GrossAmount was defined in the calculate function instead of in the outer scope. Therefor, it was not reachable in the discountAmt function.
Here is your fixed code, except with the document.writes removed so that it can run in the sandbox:
var ProductType;
var ProductQty;
var ProductPrice;
var DiscountPercent;
var TotalAmount;
var GrossAmount;
function calculate() {
ProductType = prompt("Please enter the type of product you require!").toUpperCase();
ProductQty = prompt("Please enter the number of products you require!");
elsestatement();
ProductQty = parseInt(ProductQty);
GrossAmount = ProductPrice * ProductQty;
GrossAmount = parseInt(GrossAmount);
discountAmt();
var DiscountAmount = GrossAmount - GrossAmount * DiscountPercent;
var TotalAmount = GrossAmount * DiscountPercent;
}
function elsestatement(){
if (ProductType == 'A') {
ProductPrice = 100;
} else if (ProductType == 'B') {
ProductPrice = 75;
} else if (ProductType == 'C'){
ProductPrice = 50;
} else {}
if (ProductQty < 1|| ProductQty > 100) {}
console.log('ProductPrice: ', ProductPrice);
}
function discountAmt() {
if (GrossAmount < 200) {
DiscountPercent = '0';
} else if (GrossAmount >= 200 && GrossAmount <= 399.99) {
DiscountPercent = '.05';
} else if (GrossAmount >= 400 && GrossAmount <= 599.99) {
DiscountPercent = '.075';
} else if (GrossAmount >= 600) {
DiscountPercent = '.1';
}
console.log('DiscountPercent: ', DiscountPercent);
}
calculate();

Obviously you are not closing the elsestatement function ie } is missing. and manage the code like this
change
<!DOCTYPE html>
<html>
<title>Product</title>
<body>
<h1>Product Calc</h1>
<script src="Product.js"> </script>
<script>calculate()</script>
<script>elsestatement()</script>
<script>discountAmt()</script>
</body>
to
<!DOCTYPE html>
<html>
<title>Product</title>
<script src="Product.js"> </script>
<body>
<h1>Product Calc</h1>
</body>
<script>
$(function(){
calculate();
});
</script>

Related

Why does Javascript give me a uncaught type null error?

I'm having some trouble with my Javscript for a project (Its own document we're not allowed to use inline JS) my only that I can find while attempting to execute my program is this
"payment.js:182 Uncaught TypeError: Cannot set property 'onsubmit' of null
at init (payment.js:182)".
Now this error does not show up on JSHint when I verify my code so I don't understand how to fix it, it would be great if someone could give me some help. Heres the code:
"use strict";
//validate form inputs from payment.html
function validate() {
var errMsg = "";
var result = true; //assumes no errors
//assign elements to variables
var mastercard_check = document.getElementById("mastercard").checked;
var visa_check = document.getElementById("visa").checked;
var express_check = document.getElementById("express").checked;
var credit_name = document.getElementById("credit_name").value;
var credit_number = document.getElementById("credit_number").value;
var credit_expiry = document.getElementById("credit_expiry").value;
var credit_vv = document.getElementById("credit_vv").value;
//validations for form
if (!(mastercard_check || visa_check || express_check)) {
errMsg += "Please choose a card type\n";
result = false;
}
if (credit_name.length > 40) {
errMsg += "Please enter a name for your credit card between 1-40 characters\n";
result = false;
}
else if (!credit_name.match(/^[a-zA-Z ]+$/)) {
errMsg += "Credit card name can only contain alpha characters\n";
result = false;
}
if (isNaN(credit_number)) {
errMsg = errMsg + "Credit card number must contain digits only\n";
result = false;
}
else if (credit_number.length < 15 || credit_number.length > 16){
errMsg = errMsg + "Credit card number must contian either 15 or 16 digits\n";
result = false;
}
else {
var tempMsg = checkCardNumber(credit_number);
if (tempMsg != "") {
errMsg += tempMsg;
result = false;
}
}
if (!credit_expiry.match(/^\d{2}-\d{2}$/)) {
errMsg = errMsg + "Credit Card expiry must follow the format mm-yy\n";
result = false;
}
if (!credit_vv) {
errMsg = errMsg + "Please enter a Credit Card Verification Value\n";
result = false;
}
if (errMsg != "") {
alert(errMsg);
}
return result;
}
//obtain the credit card type
function getCardType() {
var cardType = "Unknown";
var cardArray = document.getElementById("credit_type").getElementsByTagName("input");
for(var i = 0; i < cardArray.length; i++) {
if (cardArray[i].checked) {
cardType = cardArray[i].value;
}
}
return cardType;
}
//check hte card number matches the chosen card type
function checkCardNumber(credit_number) {
var errMsg = "";
var card = getCardType();
switch(card) {
case "visa":
if (!(credit_number.length == 16)) {
errMsg = "Visa number must contian 16 digits\n";
}
else if (!credit_number.match(/^(4).*$/)) {
errMsg = "Visa number must start with a 4. \n";
}
break;
case "mastercard":
if (!(credit_number.length == 16)) {
errMsg = "Mastercard number must contian 16 digits\n";
}
else if (!credit_number.match(/^(51|52|53|54|55).*$/)) {
errMsg = "Mastercard number must start with digits 51 through 55. \n";
}
break;
case "express":
if (!(credit_number.length == 15)) {
errMsg = "American Express number must contian 15 digits\n";
}
else if (!credit_number.match(/^(34|37).*$/)) {
errMsg = "American Express number must start with 34 or 37. \n";
}
break;
}
return errMsg;
}
//calculate total cost using the meal size and quantity chosen
function calcCost(size, quantity){
var cost = 0;
if (size.search("three") != -1) cost = 100;
if (size.search("four")!= -1) cost += 150;
if (size.search("five")!= -1) cost += 200;
}
//get the stored values
function getInfo(){
var cost = 0;
if(sessionStorage.firstname != undefined){
document.getElementById("confirm_name").textContent = sessionStorage.firstname + " " + sessionStorage.lastname;
document.getElementById("confirm_address").textContent = sessionStorage.address + " " + sessionStorage.suburb + " " + sessionStorage.state + " " + sessionStorage.postcode;
document.getElementById("confirm_details").textContent = sessionStorage.email + " " + sessionStorage.phone;
document.getElementById("confirm_preferred").textContent = sessionStorage.preferred;
document.getElementById("confirm_package").textContent = sessionStorage.package;
document.getElementById("confirm_size").textContent = sessionStorage.size;
document.getElementById("confirm_quantity").textContent = sessionStorage.quantity;
cost = calcCost(sessionStorage.size, sessionStorage.quantity);
document.getElementById("firstname").value = sessionStorage.firstname;
document.getElementById("lastname").value = sessionStorage.lastname;
document.getElementById("street").value = sessionStorage.street;
document.getElementById("suburb").value = sessionStorage.suburb;
document.getElementById("state").value = sessionStorage.state;
document.getElementById("postcode").value = sessionStorage.postcode;
document.getElementById("phone").value = sessionStorage.phone;
document.getElementById("email").value = sessionStorage.email;
document.getElementById("preferred").value = sessionStorage.preferred;
document.getElementById("deal").value = sessionStorage.deal;
document.getElementById("quality").value = sessionStorage.quality;
document.getElementById("quantity").value = sessionStorage.quantity;
document.getElementById("extrabags").value = sessionStorage.extrabags;
document.getElementById("accomodation").value = sessionStorage.accomodation;
document.getElementById("travel").value = sessionStorage.travel;
document.getElementById("prohibiteditems").value = sessionStorage.prohibiteditems;
document.getElementById("disabilityprecaution").value = sessionStorage.disabilityprecaution;
}
}
function cancelBooking() {
window.location = "index.html";
}
function init() {
getInfo();
var payment = document.getElementById("payment");
payment.onsubmit = validate;
var cancel = document.getElementById("cancel");
cancel.onclick = cancelBooking;
}
window.onload = init;
It might be that the ID at var payment = document.getElementById("payment"); is wrong and JS can't find it, also if you are calling some function you should do it like this payment.onsubmit = validate(); check that the ID is correct.
make sure your <script> tag is in the last before the </body> tag. like below
<html>
<head>
</head>
<body>
<form>
</form>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
but not like this
<html>
<head>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<form>
</form>
</body>
</html>

error message instead of NaN output and negative 'Nett Payment' output

var vDiscountPercent;
var vGrossPayment;
var vTicketType;
vTicketType = prompt(" What type of Tickets is required?");
document.write("The Ticket Type is: " + vTicketType);
var vTicketQty;
vTicketQty = prompt("How many Tickets are required?");
document.write("<br/>");
document.write("The Ticket Qty is: " + vTicketQty + "<br/>");
var vTicketQty = parseInt(vTicketQty);
if (isNaN(parseInt(vTicketQty))) {
vTicketQty = 0;
}
if (vTicketQty <= 0) {
document.write("Invalid Qty" + "<br/>");
} else {
vTicketPrice = calcPrice(vTicketType);
if (vTicketPrice == -1) {
document.write("Invalid Ticket Type" + "<br/>");
} else {
document.write("Ticket Price is: " + vTicketPrice + "<br/>");
}
var vTotalPayment = calcTotal(vTicketPrice, vTicketQty);
if (vTotalPayment > 0) {
document.write("Total payment required is: $" + vTotalPayment + "<br/>");
} else {
document.write("Invalid data supplied" + "<br/>");
}
}
function calcTotal(vTicketPrice, vTicketQty) {
return vTicketPrice * vTicketQty;
}
function calcPrice(vTicketType) {
var vTicketPrice;
if (vTicketType.toLowerCase() == "a") {
vTicketPrice = 100;
} else if (vTicketType.toLowerCase() == "b") {
vTicketPrice = 75;
} else if (vTicketType.toLowerCase() == "c") {
vTicketPrice = 50;
} else {
vTicketPrice = -1;
}
return vTicketPrice;
}
vGrossPayment = vTotalPayment;
var vGrossPayment = calcDiscountPercent(vGrossPayment);
function calcDiscountPercent(vGrossPayment) {
if (vGrossPayment < 200) {
document.write("Discount Percent: 0%");
vDiscountPercent = 0;
} else if (vGrossPayment < 400) {
document.write("Discount Percent: 5%");
vDiscountPercent = 0.05;
} else if (vGrossPayment < 600) {
document.write("Discount Percent: 7.5%");
vDiscountPercent = 0.075;
} else if (vGrossPayment > 600) {
document.write("Discount Percent: 10%");
vDiscountPercent = 0.10;
} else {
document.write("No discount");
}
return vDiscountPercent;
}
var applyDiscount = applyDiscount(vTotalPayment, vDiscountPercent);
function applyDiscount(vTotalPayment, vDiscountPercent) {
return vTotalPayment * (vDiscountPercent * 100) / 100;
}
document.write("<br/>" + "Discount Amount: $" + applyDiscount);
var vNettPayment = calcDiscountAmount(vTotalPayment, applyDiscount);
function calcDiscountAmount(vGrossPayment, vDiscountPercent) {
return vTotalPayment - applyDiscount;
}
document.write("<br/>" + "Nett Payment: $" + vNettPayment);
At the moment when I enter a value that isn't between 1 to 100 in 'vTicketQty' the output is 'NaN' for 'Nett Payment' and 'Discount Amount', how do I get the output value to show an error message instead of NaN?
Also when I don't enter 'a' , 'b' or 'c' for 'vTicketType' the output for 'Nett Payment" is negative, again how do I get the output to show an error message instead?
use like this .
var applyDiscount = applyDiscount(vTotalPayment, vDiscountPercent)|0;
var vNettPayment = calcDiscountAmount(vTotalPayment, applyDiscount)|0;
variable is invalid it's return with '0'
var vDiscountPercent;
var vGrossPayment;
var vTicketType;
vTicketType = prompt(" What type of Tickets is required?");
document.write("The Ticket Type is: " + vTicketType);
var vTicketQty;
vTicketQty = prompt("How many Tickets are required?");
document.write("<br/>");
document.write("The Ticket Qty is: " + vTicketQty + "<br/>");
var vTicketQty = parseInt(vTicketQty);
if (isNaN(parseInt(vTicketQty))) {
vTicketQty = 0;
}
if (vTicketQty <= 0) {
document.write("Invalid Qty" + "<br/>");
} else {
vTicketPrice = calcPrice(vTicketType);
if (vTicketPrice == -1) {
document.write("Invalid Ticket Type" + "<br/>");
} else {
document.write("Ticket Price is: " + vTicketPrice + "<br/>");
}
var vTotalPayment = calcTotal(vTicketPrice, vTicketQty);
if (vTotalPayment > 0) {
document.write("Total payment required is: $" + vTotalPayment + "<br/>");
} else {
document.write("Invalid data supplied" + "<br/>");
}
}
function calcTotal(vTicketPrice, vTicketQty) {
return vTicketPrice * vTicketQty;
}
function calcPrice(vTicketType) {
var vTicketPrice;
if (vTicketType.toLowerCase() == "a") {
vTicketPrice = 100;
} else if (vTicketType.toLowerCase() == "b") {
vTicketPrice = 75;
} else if (vTicketType.toLowerCase() == "c") {
vTicketPrice = 50;
} else {
vTicketPrice = -1;
}
return vTicketPrice;
}
vGrossPayment = vTotalPayment;
var vGrossPayment = calcDiscountPercent(vGrossPayment);
function calcDiscountPercent(vGrossPayment) {
if (vGrossPayment < 200) {
document.write("Discount Percent: 0%");
vDiscountPercent = 0;
} else if (vGrossPayment < 400) {
document.write("Discount Percent: 5%");
vDiscountPercent = 0.05;
} else if (vGrossPayment < 600) {
document.write("Discount Percent: 7.5%");
vDiscountPercent = 0.075;
} else if (vGrossPayment > 600) {
document.write("Discount Percent: 10%");
vDiscountPercent = 0.10;
} else {
document.write("No discount");
}
return vDiscountPercent;
}
var applyDiscount = applyDiscount(vTotalPayment, vDiscountPercent)|0;
function applyDiscount(vTotalPayment, vDiscountPercent) {
return vTotalPayment * (vDiscountPercent * 100) / 100;
}
if(applyDiscount){
document.write("<br/>" + "Discount Amount: $" + applyDiscount)
}
else{
document.write("<br/>Error-something not right in Discount Amount")
}
var vNettPayment = calcDiscountAmount(vTotalPayment, applyDiscount)|0;
function calcDiscountAmount(vGrossPayment, vDiscountPercent) {
return vTotalPayment - applyDiscount;
}
if(vNettPayment){
document.write("<br/>" + "Nett Payment: $" + vNettPayment);
}
else{
document.write("<br/>Error-something not right in Nett Payment ")
}

Javascript: assigning an input letter a specific value

I'm having trouble assigning an input a certain value. For example, when the user enters a letter through the TicketType prompt, I want that letter to be converted into a number. So say they enter 'B' as their TicketType, I then want 'B' to be converted into 50 so I can latter calculate a total cost. At the moment TotalPayment is only displaying NaN and I'm so confused.
This is my JavaScript Code:
function ticket() {
var TicketType;
TicketType = prompt("Please enter the type of ticket you require!");
document.write("<br>");
var TicketQty;
TicketQty = prompt("Please enter the number of tickets you require!");
TicketQty = parseInt(TicketQty);
document.write("Number of Tickets:" + TicketQty);
document.write("<br>");
var TotalPayment =(TicketPrice) * (TicketQty);
document.write("Total Payment is:" + TotalPayment);
var TicketPrice;
TicketPrice = parseInt(TicketPrice);
if (TicketType == A) {
TicketPrice == 100;
}
else if (TicketType == B) {
TicketPrice == 75;
}
else if (TicketType == C){
TicketPrice == 50;
}
else {
document.write("Invalid Ticket Type");
}
}
This is my HTML Code:
<html>
<title>Ticket</title>
<h1>Ticket</h1>
<script src="test.js"> </script>
<script>calculate()</script>
</body>
Try the following:
var TicketType;
var TicketQty;
var TicketPrice;
function calculateticket() {
TicketType = prompt("Please enter the type of ticket you require!");
document.write("<br>");
TicketQty = prompt("Please enter the number of tickets you require!");
testType();
}
calculateticket();
function testType(){
if(TicketType =='A' || TicketType == 'B' || TicketType == 'C'){
if (TicketType == 'A') {
TicketPrice = 100;
} else if (TicketType == 'B') {
TicketPrice = 75;
} else if (TicketType == 'C'){
TicketPrice = 50;
}
TicketQty = parseInt(TicketQty);
document.body.innerHTML += '<span id="text1"></span>';
document.getElementById('text1').innerHTML = 'Total Payment is: '+TicketQty;
document.write("<br>");
var TotalPayment =(TicketPrice) * (TicketQty);
document.body.innerHTML += '<span id="text2"></span>';
document.getElementById('text2').innerHTML = 'Total Payment is: '+TotalPayment;
TicketPrice = parseInt(TicketPrice);
}
else {
if(document.getElementById('text1') != null){
document.getElementById('text1').innerHTML = '';
}
if(document.getElementById('text2') != null){
document.getElementById('text2').innerHTML = '';
}
document.write("Invalid Ticket Type");
}
}
You need to change two things:
1: String comparation
if (TicketType == A)
to
if (TicketType == 'A')
2: wrong assign
TicketPrice == 100
to
TicketPrice = 100
Your string comparison is completely wrong. I'm confining my answer to that because it's what you were asking about.
if (TicketType == A) {
Needs to be:
if (TicketType === "A") {
Also, you have to be clear on assignment '=' vs. comparison '=='.
Whole section should be more like this:
if (TicketType === "A") {
TicketPrice = 100;
} else if (TicketType === "B") {
TicketPrice = 75;
} else if (TicketType === "C")
TicketPrice = 50;
else {
document.write("Invalid Ticket Type");
}
Look into switch statements when you have a chained if-then-elseif
There are other things wrong with your code. Here's a jsfiddle with some fixes and improvements.

showing variable value in <p> paragraph using getElementById.innerHTML in Javascript

I'm trying to write a Blackjack code using Javascript, and showing the result in an HTML page. I have written the logic already, but I can't get to show the results in paragraph by ID, using getElementById.innerHTML. I don't know how to make it right. Could you please help me with this? I'm running out of time :(. here's the code:
<!DOCTYPE html>
<html>
<title>Welcome to Blackjack</title>
<!--<link href="style.css" rel="stylesheet" type="text/css">
<!-- <script src="bj.js"></script> -->
<head>
<script>
var PlayerScore = 0;
var DealerScore = 0;
var Winner = "Nobody";
var AskAgain = true;
function random(maxValue)
{
return Math.floor(Math.random() * maxValue) + 1;
}
function pickSuit()
{
suit = random(4);
if(suit == 1)
return "Spades";
if(suit == 2)
return "Clubs";
if(suit == 3)
return "Diamonds";
return "Hearts";
}
function cardName(card)
{
if(card == 1)
return "Ace";
if(card == 11)
return "Jack";
if(card == 12)
return "Queen";
if(card == 13)
return "King";
return ("" + card);
}
function cardValue(card)
{
if(card == 1)
return 11;
if(card > 10)
return 10;
return card;
}
function PickACard(strWho)
{
card = random(13);
suit = pickSuit();
alert(strWho + " picked the " + cardName(card) + " of " + suit);
return cardValue(card);
}
function Dealer()
{
while(DealerScore < 17)
{
DealerScore = DealerScore + PickACard("Dealer");
}
}
function User()
{
PlayerScore = PlayerScore + PickACard("You");
}
function LookAtHands(Winner)
{
if(DealerScore > 21)
{
alert("House busts! You win!");
Winner = "You";
}
else
if((PlayerScore > DealerScore) && (PlayerScore <= 21))
{
alert("You win!");
Winner = "You";
}
else
if(PlayerScore == DealerScore)
{
alert("Push!");
Winner = "Tie";
}
else
{
alert("House wins!");
Winner = "House";
}
}
Dealer();
alert("Dealer's score is: " + DealerScore);
document.getElementById('DealerScore').innerHTML = DealerScore;
User();
alert("Your score is: " + PlayerScore);
document.getElementById("DealerScore").innerHTML = "Dealer's score is: " + DealerScore;
while (AskAgain == true )
{
var answer = confirm("Do you want to draw a card?")
if (answer == true)
{
User();
alert("Your score is: " + PlayerScore);
document.getElementById("PlayerScore").innerHTML = "Your score is: " + PlayerScore;
if (PlayerScore < 21)
{AskAgain = true;}
else
{AskAgain = false;}
}
else
{
AskAgain = false;
}
}
LookAtHands();
</script>
</head>
<body>
<div><p>Welcome to our Blackjack Table!</p>
<p id="PlayerScore">Your Score is: </p>
<p id="DealerScore">Dealer's Score is: </p>
</div>
</body>
</html>
As #nnnnnn has mentioned that your html tags are not even loaded when your JS has executed and hence the issue. Try something like below to correct the issue:
<!DOCTYPE html>
<html>
<title>Welcome to Blackjack</title>
<!--<link href="style.css" rel="stylesheet" type="text/css">
<!-- <script src="bj.js"></script> -->
<head>
<script>
var PlayerScore = 0;
var DealerScore = 0;
var Winner = "Nobody";
var AskAgain = true;
function random(maxValue)
{
return Math.floor(Math.random() * maxValue) + 1;
}
function pickSuit()
{
suit = random(4);
if(suit == 1)
return "Spades";
if(suit == 2)
return "Clubs";
if(suit == 3)
return "Diamonds";
return "Hearts";
}
function cardName(card)
{
if(card == 1)
return "Ace";
if(card == 11)
return "Jack";
if(card == 12)
return "Queen";
if(card == 13)
return "King";
return ("" + card);
}
function cardValue(card)
{
if(card == 1)
return 11;
if(card > 10)
return 10;
return card;
}
function PickACard(strWho)
{
card = random(13);
suit = pickSuit();
alert(strWho + " picked the " + cardName(card) + " of " + suit);
return cardValue(card);
}
function Dealer()
{
while(DealerScore < 17)
{
DealerScore = DealerScore + PickACard("Dealer");
}
}
function User()
{
PlayerScore = PlayerScore + PickACard("You");
}
function LookAtHands(Winner)
{
if(DealerScore > 21)
{
alert("House busts! You win!");
Winner = "You";
}
else
if((PlayerScore > DealerScore) && (PlayerScore <= 21))
{
alert("You win!");
Winner = "You";
}
else
if(PlayerScore == DealerScore)
{
alert("Push!");
Winner = "Tie";
}
else
{
alert("House wins!");
Winner = "House";
}
}
</script>
</head>
<body>
<div><p>Welcome to our Blackjack Table!</p>
<p id="PlayerScore">Your Score is: </p>
<p id="DealerScore">Dealer's Score is: </p>
</div>
<script>
Dealer();
alert("Dealer's score is: " + DealerScore);
document.getElementById('DealerScore').innerHTML = DealerScore;
User();
alert("Your score is: " + PlayerScore);
document.getElementById("DealerScore").innerHTML = "Dealer's score is: " + DealerScore;
while (AskAgain == true )
{
var answer = confirm("Do you want to draw a card?")
if (answer == true)
{
User();
alert("Your score is: " + PlayerScore);
document.getElementById("PlayerScore").innerHTML = "Your score is: " + PlayerScore;
if (PlayerScore < 21)
{AskAgain = true;}
else
{AskAgain = false;}
}
else
{
AskAgain = false;
}
}
LookAtHands();
</script>
</body>
</html>
your script is loading before the document that has the elements in it. Enclose your script in:
window.onload=function() {
//all of your JavaScript code
}

vertical bar chart with validation

I changed my code abit, because i want some validation inside my code. before the the bars had the "%" on it and the name typed in under the bar, now if i type in 2 participants, it creates 4 bars instead of 2. At the place where the names should be is an "undefined" and where the % should be is NaN%. Does someone know where the mistake is?
<head>
<title>examAnalysis</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<style type="text/css">
div {
float: left; margin-right: 10px;
}
div p {
text-align: center;
}
</style>
<script type="text/javascript">
var participant = [];
var maxPoints = 200;
var barWidth = 50;
function gatherData() {
var name;
var points;
while (name = window.prompt('Please enter the name of the participant:')) {
name = name.replace(/\s+/g, '')
if ((/[^A-Z\s\-\']/gi.test(name)) || (name == '')) {
alert ('You must enter a valid name! ');
} else {
participant.push({name: name});
while(points = window.prompt('Please enter the achieved points of the participant:')) {
points = parseInt(points, 10);
if ((/[^0-9\s\-\']/gi.test(points)) || (points == '')) {
alert ('You must enter a valid number! ');
} else {
participant.push({points: points});
break;
}
}
}
}
createChart();
};
function createChart ()
{
var i = 0;
var len = participant.length;
var bar = null;
var container = document.getElementById('chart');
container.innerHTML='';
while (i < len)
{
bar = document.createElement('div');
bar.style.width = barWidth + 'px';
bar.style.backgroundColor = getRandomColor();
bar.style.float = 'left';
bar.style.marginRight = '10px';
bar.style.height = ((participant[i].points / maxPoints) * 200) + 'px';
bar.style.marginTop = 200 - parseInt(bar.style.height) + 'px';
percent = ((participant[i].points / maxPoints) * 100) + '%';
bar.innerHTML = ['<p style="margin-top: ' + (parseInt(bar.style.height) - 17) + 'px">', percent, '<br />', participant[i].name, '</p>'].join('');
container.appendChild(bar);
i = i + 1;
}
};
function getRandomColor () {
return ['rgb(', Math.floor(Math.random() * 255), ', ', Math.floor(Math.random() * 255), ', ', Math.floor(Math.random() * 255), ')'].join('');
};
</script>
</head>
<body>
<button onclick="gatherData()">Add Participant</button>
<h4>Chart</h4>
<div id="chart"></div>
</body>
Try this:
function gatherData()
{
var name = window.prompt('Please enter the name of the participant:');
name = name.replace(/\s+/g, '');
if ((/[^A-Z\s\-\']/gi.test(name)) || (name == '') || (name == 'undefined'))
{
alert ('You must enter a valid name! ');
return;
}
var points = window.prompt('Please enter the achieved points of the participant:');
points = parseInt(points, 10);
if ((/[^0-9\s\-\']/gi.test(points)) || (points == ''))
{
alert ('You must enter a valid number! ');
return;
}
participant.push({name: name, points: points});
createChart();
};

Categories

Resources