Getting Order to Appear on Confirm Alert Box - javascript

So I got this function:
function displayTotal() {
var r = confirm("Are you sure you want to place this order?");
if (r == true) {
x = "Your order has been placed!" + document.forms["drinkList"].reset();
} else {
x = ""
}
}
What I am trying to do is get the total cost of all items ordered, along with what item, quantity, and price per item.
I am using this function for example, to get the total for a particular drink.
var totalEstimate = 0;
var blackCost = 0;
function calcBlack() {
totalEstimate -= blackCost;
blackCost = document.forms.quant1.value * 0.99;
totalEstimate += blackCost;
document.drinkList.order.value = "$" + totalEstimate;
}
I have tried:
function displayTotal() {
var r = confirm("Are you sure you want to place this order?" + calcBlack());
if (r == true) {
x = "Your order has been placed!" + document.forms["drinkList"].reset();
} else {
x = ""
}
}
But that didn't display anything. Could anyone point me in the right direction? Thanks.
I am calling displayTotal() here:
<input type="button" value="Order" name="order" onclick="displayTotal()" />

calcBlack doesn't return anything, you'll need to modify it to return the data you want to display in the confirm alert box.
function calcBlack() {
totalEstimate -= blackCost;
blackCost = document.forms.quant1.value * 0.99;
totalEstimate += blackCost;
document.drinkList.order.value = "$" + totalEstimate;
return totalEstimate;
}

Related

When i try to use the variable changed within an if statement it returns NaN

I'm trying to make a neural network but when I try to retrieve the changed state of the variable from the if statement in my js code it just retrieves the state at which I declared the variable instead, is there a fix for this? Also, if anyone knows of a neater way to do those inputs that would be helpful as well.
Edit: I could probably use the switch condition but I'm relatively new to js so I'd need some help or an example of how to implement that into my code.
JS:
var input1;
var input2;
var input3;
function myFunction1() {
if(input1 != 1) {
input1 = 1;
}
else if(input1 != 0) {
input1 = 0;
}
document.getElementById("in1state").innerHTML = input1;
}
function myFunction2() {
if(input2 != 1) {
input2 = 1;
}
else if(input2 != 0) {
input2 = 0;
}
document.getElementById("in2state").innerHTML = input2;
}
function myFunction3() {
if(input3 != 1) {
input3 = 1;
}
else if(input3 != 0) {
input3 = 0;
}
document.getElementById("in3state").innerHTML = input3;
}
var neuron1, neuron2, neuron3, neuron4
var n1Weight, n2Weight, n3Weight, n4Weight
var n1Bias, n2Bias, n3Bias, n4Bias
n1Weight = 0.6;
n2Weight = 0.2;
n3Weight = 1.0;
n4Weight = 0.6;
n1Bias = 0.4;
n2Bias = 0.8;
n3Bias = 1.0;
n4Bias = 0.6;
neuron1 = (input1 * n1Weight) + (input2 * n1Weight) + (input3 * n1Weight) + n1Bias;
neuron2 = (input1 * n2Weight) + (input2 * n2Weight) + (input3 * n2Weight) + n2Bias;
neuron3 = (input1 * n3Weight) + (input2 * n3Weight) + (input3 * n3Weight) + n3Bias;
neuron4 = (input1 * n4Weight) + (input2 * n4Weight) + (input3 * n4Weight) + n4Bias;
function myRun() {
document.getElementById("oof").innerHTML = neuron1 + " " + neuron2 + " " + neuron3 + " " + neuron4;
}
'''
NAN meaning, not a number.
That's because input1, input2, and input3 are strings. In Javascript, you can't multiply an Integer with String
1 is different than "1"
so to fix this, you would have to parse input1, input2, and input3 by using parseInt
parseInt(input1);

Can't determine reason for NaN output

first time asking a question, long-time lurker. Entry CS student here, first semester working with HTML and JS, and am working on a project that essentially checks the value of some checkboxes, radio buttons, and textboxes, formats some variables based on inputs and values, and outputs that information in a display section. The major issue being, my .js script is resulting in an output in NaN in places I would expect a number and I can't determine as to why. Below is the script, I can amend the html page as well if needed.
But Essentially, in the displayOutput function, the ranging from accessoriesOut to amountOut are giving me a display of NaN and I'm at a loss.
// Declares global variables and their default values.
const STEREO_COST=425.76;
const INTERIOR_COST=987.41;
const NAVIGATION_COST=1741.23;
const STANDARD_FINISH=0;
const PEARLIZED_FINISH=345.72;
const CUSTOM_FINISH =599.99;
const EXCELLENT_CONDITION=1.0;
const GOOD_CONDITION=0.9;
const FAIR_CONDITION=0.8;
const POOR_CONDITION=0.6;
const SALES_TAX_RATE=0.08;
const TRADE="trade";
const ACCESSORIES="accessories";
const SUBTOTAL="subtotal";
const TAX="tax";
const AMOUNT="amount";
const PRICE="price";
const NAME="name";
// Establishes pricing and condition values with the corresponding user inputs.
function pageLoad(){
document.getElementById("stereoDiv").innerHTML += FormatCurrencyText(STEREO_COST);
document.getElementById("interiorDiv").innerHTML += FormatCurrencyText(INTERIOR_COST);
document.getElementById("navigationDiv").innerHTML += FormatCurrencyText(NAVIGATION_COST);
document.getElementById("standardDiv").innerHTML += FormatCurrencyText(STANDARD_FINISH);
document.getElementById("pearlizedDiv").innerHTML += FormatCurrencyText(PEARLIZED_FINISH);
document.getElementById("customDiv").innerHTML += FormatCurrencyText(CUSTOM_FINISH);
document.getElementById("excellentDiv").innerHTML += FormatPercentText(EXCELLENT_CONDITION);
document.getElementById("goodDiv").innerHTML += FormatPercentText(GOOD_CONDITION);
document.getElementById("fairDiv").innerHTML += FormatPercentText(FAIR_CONDITION);
document.getElementById("poorDiv").innerHTML += FormatPercentText(POOR_CONDITION);
}
// Formats money value for output.
function FormatCurrency(amt){
return "$" + amt.toFixed(2); }
// Formats the output and text for currency.
function FormatCurrencyText(amt){
return " (" + FormatCurrency(amt) + ")"; }
// Formats the percent values for display.
function FormatPercentText(pct){
return " (" + (pct * 100).toFixed(2) +"%)"; }
// Determines which trade-in choice is made, and assigns it to and returns a variable.
function getConditionRate() {
var rate;
if (document.getElementById("excellent").checked==true){
rate=EXCELLENT_CONDITION; }
if (document.getElementById("good").checked==true){
rate=GOOD_CONDITION; }
if (document.getElementById("fair").checked==true){
rate=FAIR_CONDITION; }
if (document.getElementById("poor").checked==true){
rate=POOR_CONDITION; }
return rate; }
// Determines which accessories are selected, accumulates and returns a total.
function getAccessoriesTotal() {
var total;
if (document.getElementById("stereo").checked==true){
total += parseFloat(STEREO_COST); }
if (document.getElementById("interior").checked==true){
total += parseFloat(INTERIOR_COST); }
if (document.getElementById("navigation").checked==true){
total += parseFloat(NAVIGATION_COST); }
return total; }
// Determines which finish choice is made, assigns it to a variable for return.
function getFinishAmount(){
var amount;
if (document.getElementById("standard").checked==true){
amount = parseFloat(STANDARD_FINISH); }
if (document.getElementById("pearlized").checked==true){
amount = parseFloat(PEARLIZED_FINISH); }
if (document.getElementById("custom").checked==true){
amount = parseFloat(CUSTOM_FINISH); }
return amount; }
// Determines whether a trade-in was selected, enables/disables controls accordingly.
function EnableTradeIn(){
var isChecked = document.querySelector('[id="tradein"]:checked');
if (isChecked) {
document.getElementById("excellent").disabled=false;
document.getElementById("good").disabled=false;
document.getElementById("fair").disabled=false;
document.getElementById("poor").disabled=false;
document.getElementById("tradeinBox").disabled=false; }
else {
document.getElementById("excellent").disabled=true;
document.getElementById("good").disabled=true;
document.getElementById("fair").disabled=true;
document.getElementById("poor").disabled=true;
document.getElementById("tradeinBox").disabled=true;
document.getElementById("excellent").focus();
document.getElementById("tradeinBox").value=""; }
}
//
function DisplayOutput(accessoriesTotal, tradeinAllowance, subtotal, taxAmount, amountDue, price, name) {
document.getElementById("nameOut").innerHTML=name;
document.getElementById("priceOut").innerHTML=FormatCurrency(price);
document.getElementById("accessoriesOut").innerHTML=FormatCurrency(accessoriesTotal);
document.getElementById("tradeinOut").innerHTML=FormatCurrency(tradeinAllowance);
document.getElementById("subtotalOut").innerHTML=FormatCurrency(subtotal);
document.getElementById("salestaxOut").innerHTML=FormatCurrency(taxAmount);
document.getElementById("amountOut").innerHTML=FormatCurrency(amountDue);
}
function CalculateMain(){
var accessoriesTotal = 0;
var tradeinAllowance = 0;
var subtotal = 0;
var taxAmount = 0;
var amountDue = 0;
var isTradein;
var conditionRate = 0;
var tradeinAmount = 0;
var conditionRate = 0;
var price = document.getElementById("priceBox").value;
var name = document.getElementById("nameBox").value;
//Validate that name is entered
if (name == "" || document.getElementById("nameBox").value==undefined){
document.getElementById("nameError").style.border="1px solid red";
document.getElementById("nameError").innerHTML = "No name entered";
return; }
else{
document.getElementById("nameError").style.border="";
document.getElementById("nameError").innerHTML = ""; }
//Validate price
if (isNaN(price) || price == "" || price < 0){
document.getElementById("priceError").style.border="1px solid red";
document.getElementById("priceError").innerHTML = "Price is not valid";
return; }
else {
price = parseFloat(price);
document.getElementById("priceError").style.border="";
document.getElementById("priceError").innerHTML = "";
}
//Determine if there is a trade-in
isTradein = document.getElementById("tradein").checked;
if (isTradein) {
tradeinAmount = parseFloat(document.getElementById("tradeinBox").value);
conditionRate = getConditionRate(); }
//Validate trade in amount
if (isNaN(tradeinAmount) || tradeinAmount == "" || tradeinAmount < 0) {
document.getElementById("tradeinError").style.border = "1px solid red";
document.getElementById("tradeinError").innerHTML = "Tradein amount is not valid";
return; }
else {
document.getElementById("tradeinError").style.border = "";
document.getElementById("tradeinError").innerHTML = ""; }
//Calculate trade-in allowance (will be 0 if check box is not checked)
tradeinAllowance = parseFloat(tradeinAmount) * parseFloat(conditionRate);
//Validate trade in allowance is not greater than price
if (tradeinAllowance > price){
document.getElementById("tradeinError").style.border="1px solid red";
document.getElementById("tradeinError").innerHTML = "Trade in more than Price";
return; }
else {
document.getElementById("tradeinError").style.border="";
document.getElementById("tradeinError").innerHTML = "";
}
accessoriesTotal = getAccessoriesTotal() + getFinishAmount();
subtotal = price + accessoriesTotal - tradeinAllowance;
taxAmount = subtotal * SALES_TAX_RATE;
amountDue = subtotal + taxAmount;
//Call DisplayOutput
DisplayOutput(parseFloat(accessoriesTotal), parseFloat(tradeinAllowance), parseFloat(subtotal), parseFloat(taxAmount), parseFloat(amountDue), price, name);
}
In the getAccessoriesTotal function, you don't have total defined before trying to add to it. I assume you'd want to default it to 0. (Note: I'd also recommend defaulting amount in getFinishAmount to something).
function getAccessoriesTotal() {
var total = 0;
if (document.getElementById("stereo").checked==true){
total += parseFloat(STEREO_COST); }
if (document.getElementById("interior").checked==true){
total += parseFloat(INTERIOR_COST); }
if (document.getElementById("navigation").checked==true){
total += parseFloat(NAVIGATION_COST); }
return total;
}

Displaying buttons and printing a variable in javascript

I'm fairly new to JavaScript, but I have some experience in other languages. I've been working on making my own small project, and I'm still figuring out how some things work. I have two problems that I need help solving. The first one, is that I have a button that should appear after you get 100 points, and click the button. This is at the if (buyupgrade == 1) and the following parts of that. I want the button to appear after the conditions are met (buy the first upgrade after getting 100 points). I also want to be printing the text part of a button, but in the text, I need it to display a variable, So my button text will display some words and a variable. Thanks for the help!
<!DOCTYPE html>
<html>
<body>
<p>Click to get started!</p>
<button onclick="addPoints()">Add points</button>
<button id="btn_multiply" onclick="firstx2()" style="display:none;">x2 Multiplier. Cost: 100</button>
<button id="firstbuild" onclick="build1()" style="display:none;">Building 1. Cost 200</button>
<script>
var points = 98;
var pointMulti = 1;
var buyupgrade = 0;
var currentpoints = setInterval(pointupdate, 1000);
function addPoints() {
points += pointMulti;
var pointsArea = document.getElementById("pointdisplay");
pointsArea.innerHTML = "You have " + points + " points!";
if(points >= 100 && buyupgrade == 0) {
var multiply_button = document.getElementById("btn_multiply");
multiply_button.style.display = "inline";
}
}
function firstx2() {
if (buyupgrade == 0) {
pointMulti *= 2;
buyupgrade++;
points -= 100;
var multiplierArea = document.getElementById("multidisplay");
multiplierArea.innerHTML = "Your multiplier is: " + pointMulti + "!";
var multiply_button = document.getElementById("btn_multiply");
multiply_button.style.display = "none";
}
}
if (buyupgrade == 1) {
document.getElementById("firstbuild");
firstbuild.style.display = "inline";
function build1() {
}
}
function pointupdate() {
document.getElementById("pointdisplay").innerHTML = "You have " + points + " points!";
}
</script>
<p id="pointdisplay"></p>
<p id="multidisplay"></p>
</body>
</html>
Your code that is supposed to make the third button visible is by itself outside any function. This seems like a typo:
if (buyupgrade == 1) {
document.getElementById("firstbuild");
firstbuild.style.display = "inline";
function build1() {
}
This only gets called the first time through the program when buyupgrade == 0
I think you meant for this to be inside the function:
function firstx2() {
if (buyupgrade == 0) {
pointMulti *= 2;
buyupgrade++;
points -= 100;
var multiplierArea = document.getElementById("multidisplay");
multiplierArea.innerHTML = "Your multiplier is: " + pointMulti + "!";
var multiply_button = document.getElementById("btn_multiply");
multiply_button.style.display = "none";
}
if (buyupgrade == 1) {
var firstbuild = document.getElementById("firstbuild");
firstbuild.style.display = "inline";
// add some text to the button
firstbuild.innerText = "buyupgrade: " + buyupgrade
}
}
Also, there's a typo:
document.getElementById("firstbuild");
should probably be:
var firstbuild = document.getElementById("firstbuild");

Solve mathematical function in javascript

I have created this function for a shopping basket. To be simple, i have x products with (2 checkbox + quantity input) for each.
The first checkbox add +3, second +8, to the product price. It's like (3+8+price)*quantity. At the end of the page, i have the total result (like product1 + product2...Etc)
The problem is: If i'm posting the form with new quantities, and going back to the page, i have the default result (total price) (of course, checkbox are checked + new quantity with PHP).
Here is my function:
$(function(){
var item_prices = 0;
var total_item_prices = 0;
var total_unique_item_prices = 0;
var total_price = 0;
$.each($('*[data-item-price]'), function(index, element) {
var item_price = $(element).data("item-price");
total_unique_item_prices = parseInt($('[data-total]').html()) + item_price;
total_price = total_unique_item_prices;
$('[data-total]').html(total_unique_item_prices);
})
$.each($('*[data-item-price]'), function(index, element) {
var item_price = $(element).data("item-price");
var price_of_options = 0;
var quantity = parseInt($(element).find('input[data-quantity]').val());
$.each($(element).children().find("[data-price]"), function(index, element2) {
$(element2).click(function(){
var actual_price = parseInt($('[data-total]').html());
var actual_item_price = parseInt($(element).find('[data-item-total]').html());
var price = $(element2).data("price");
if ($(element2).is(':checkbox') && $(element2).is(':checked')) {
price_of_options += price;
$(element).find('[data-item-total]').html(actual_item_price + (price * quantity));
$('[data-total]').html(actual_price + (price * quantity));
}
else {
price_of_options -= price;
$(element).find('[data-item-total]').html(actual_item_price - (price));
$('[data-total]').html(actual_price - (price * quantity));
}
})
})
$(element).find('input[data-quantity]').bind('keyup mouseup', function () {
var new_quantity = parseInt($(element).find('input[data-quantity]').val());
var quantity_dif = new_quantity - quantity;
var actual_price = parseInt($('[data-total]').html());
if (quantity_dif > 0) {
quantity_dif = new_quantity - quantity;
$(element).find('[data-item-total]').html((item_price + price_of_options) * new_quantity);
$('[data-total]').html(actual_price + ((item_price + price_of_options) * quantity_dif));
}
else {
quantity_dif *= -1;
quantity = parseInt($(element).find('[data-quantity]').val());
$(element).find('[data-item-total]').html((item_price + price_of_options) * new_quantity);
$('[data-total]').html(actual_price - ((item_price + price_of_options) * quantity_dif));
}
quantity = parseInt($(element).find('[data-quantity]').val());
})
})
})
As I said, code is working: https://jsfiddle.net/redbean/4dy38ye4/1/ Just not when i'm reloading the webpage.
I'm not english, be kind about this. I'm trying to do the best to be clear!

JavaScript - How to make 6 individual order total functions into one

I should be using a single function for this. When the button is clicked, simply multiply each quantity by its respective price and add them together.
I'm not sure how to create a single function. I've added comments to each section to to help understand, I'm creating a basic ordering page. I have set values of cost for 5 items, the quantity is a number text field the user will enter in any whole interger.
Here's my code:
/*Array to hold QTY wanted from user*/
var dvdQTY = [0, 0, 0, 0, 0];
var movieName = new Array(5);
movieName[0] = "Star Wars";
movieName[1] = "The Empire Strikes Back";
movieName[2] = "Return of the Jedi";
movieName[3] = "The Force Awakens";
movieName[4] = "Rogue One";
/*variables to store the values entered.*/
var ep4Cost = 0;
var ep5Cost = 0;
var ep6Cost = 0;
var ep7Cost = 0;
var rogueCost = 0;
var totalEstimate = 0;
/* Array of the price variables*/
var moviePrice = new Array(5);
moviePrice[0] = 65; //Price of EP4
moviePrice[1] = 55; //Price of EP5
moviePrice[2] = 45; //Price of EP6
moviePrice[3] = 35; //Price of EP7
moviePrice[4] = 25; //Price of Rouge One
/*Function to calculate the totalEstiamte of entered values by the user at a price of $65 dollars each.*/
function calcEP4() {
totalEstimate -= ep4Cost;
dvdQTY[0] = document.movielist.dvdQTY[0].value;
ep4Cost = dvdQTY[0] * moviePrice[0];
totalEstimate += ep4Cost;
+totalEstimate;
console.log(dvdQTY);
}
/*Function to calculate the totalEstiamte of entered values by the user at a price of $55 dollars each.*/
function calcEP5() {
totalEstimate -= ep5Cost;
dvdQTY[1] = document.movielist.dvdQTY[1].value;
ep5Cost = dvdQTY[1] * moviePrice[1];
totalEstimate += ep5Cost;
+totalEstimate;
}
/*Function to calculate the totalEstiamte of entered values by the user at a price of $45 dollars each.*/
function calcEP6() {
totalEstimate -= ep6Cost;
dvdQTY[2] = document.movielist.dvdQTY[2].value;
ep6Cost = dvdQTY[2] * moviePrice[2];
totalEstimate += ep6Cost;
+totalEstimate;
}
/*Function to calculate the totalEstiamte of entered values by the user at a price of $35 dollars each.*/
function calcEP7() {
totalEstimate -= ep7Cost;
dvdQTY[3] = document.movielist.dvdQTY[3].value;
ep7Cost = dvdQTY[3] * moviePrice[3];
totalEstimate += ep7Cost;
+totalEstimate;
}
/*Function to calculate the totalEstiamte of entered values by the user at a price of $25 dollars each.*/
function calcRogue() {
totalEstimate -= rogueCost;
dvdQTY[4] = document.movielist.dvdQTY[4].value;
rogueCost = dvdQTY[4] * moviePrice[4];
totalEstimate += rogueCost;
+totalEstimate;
}
/*Function to calculate the totalEstiamte and show the results to the button "total" on click.*/`enter code here`
function myTotal()
{
var newTotal = "$" + totalEstimate;
document.getElementById("total").innerHTML = "$" + totalEstimate;
console.log(newTotal)
}
You take what varies from function to function and pass those values into a single function that uses them:
function calc(epCost, dvd, moviePrice) {
totalEstimate -= epCost;
dvd = document.movielist.dvd.value;
epCost = dvd * moviePrice;
totalEstimate += epCost;
+totalEstimate;
}
And you pass those values when you need to call the function:
calc(ep6Cost, dvdQTY[2], moviePrice[2]);

Categories