On my store, I want to offer a promotion for people who buy up to 1499, 2998, 4497, etc. (it is a multiplication of 1499);
do you recommend me use the conditional if? use switch? or what do you do in this case?
I ask you this be cause when they buy up to the values (1499,2998, etc) I need to show a div saying that the person won a promotion
I'm thinking do a multiplication of 1499 and check the total of the person is up to 1499,2998 etc, actually a make a multiplication table but I dunno how to check if is between a range
var i = 0;
document.write('<table border="1" cellspacing="0">');
for(i=1;i<10;i++) {
document.write("<tr><td>" + num + " x " + i + " = " + num*i + "</td></tr>");
}
document.write("</table>");```
The table can be there just for display.
const num = 1499;
var i = 0;
document.write('<table border="1" cellspacing="0">');
for(i=1;i<10;i++) {
document.write("<tr><td>" + num + " x " + i + " = " + num*i + "</td></tr>");
}
document.write("</table>");
To actually calculate the amount won from what the user has bought, divide the amount by 1499 and then call Math.floor on it:
const amountWon = input => Math.floor(input / 1499);
console.log(
amountWon(1498),
amountWon(1499),
amountWon(1500),
amountWon(2997),
amountWon(2998),
);
But make sure to do the calculation on the server-side as well, since none of the code you run on the client side can be trustworthy.
Related
I am working on a sort of clicker game where the user is able to buy upgrades. One such upgrade involves the user earning a certain amount of in-game currency per second, in this case 0.1. Unfortunately if the user decides to buy more than one of this upgrade it appears to rise exponentially. I feel like this might be because the setInterval() function is stacking each time, so that the first time it is 0.1 then the next its 0.1 + 0.2 so 0.3, then 0.3 + 0.2 + 0.1 so 0.6 and so on.
upgradePerSec1.onclick = function() {
if (presents >= cost1) {
presents -= cost1;
upgrade1Amount += 1;
totalPresentsSpent += cost1;
cost1 = Math.ceil(cost1Base *= 1.03 ** upgrade1Amount);
perSec += 0.1;
displayScore.innerHTML = format(presents) + " Presents delivered.";
cost1Disp.innerHTML = "<hr>Cost: " + format(cost1);
title.innerHTML = format(presents) + " Presents";
perSecDisp.innerHTML = formatPerSec(perSec) + " presents /s";
totalPresentsSpentDisp.innerHTML = format(totalPresentsSpent) + " Total presents spent";
setInterval(increment1, 1000);
} else {
alert("You don't have enough presents! Still need: " + format(cost1 - presents));
}
}
function increment1() {
presents += perSec;
totalPresents += perSec;
displayScore.innerHTML = format(presents) + " Presents delivered.";
totalPresentsDisp.innerHTML = format(totalPresents) + " Total presents delivered";
title.innerHTML = format(presents) + " Presents";
}
Here is some clarification for this code:
upgradePerSec1 = HTML button element
cost1 = the cost of this upgrade
perSec = variable to store the amount of "presents" per second
displayScore = an HTML label element
cost1Disp = an HTML label element
title = the browser tab title
format() = a function to format large numbers by adding in commas
totalPresents = the total presents without taking away costs (used for a statistics section)
I have tried replacing the perSec variable with just the number(obviously did not work) I have tried making the timing also rise but could not get the correct timing. Ive also searched many places on the web and could not find any helpful results. I saw one on stack overlfow but it did not apply to me.
You're right, the setInterval calls are stacking. To fix the issue, you should make sure you only call setInterval() once (e.g. by adding an if statement before that line checking if perSec === 0).
e.g.
upgradePerSec1.onclick = function() {
if (presents >= cost1) {
if (perSec === 0) {
setInterval(increment1, 1000);
}
presents -= cost1;
upgrade1Amount += 1;
totalPresentsSpent += cost1;
cost1 = Math.ceil(cost1Base *= 1.03 ** upgrade1Amount);
perSec += 0.1;
displayScore.innerHTML = format(presents) + " Presents delivered.";
cost1Disp.innerHTML = "<hr>Cost: " + format(cost1);
title.innerHTML = format(presents) + " Presents";
perSecDisp.innerHTML = formatPerSec(perSec) + " presents /s";
totalPresentsSpentDisp.innerHTML = format(totalPresentsSpent) + " Total presents spent";
} else {
alert("You don't have enough presents! Still need: " + format(cost1 - presents));
}
}
function increment1() {
presents += perSec;
totalPresents += perSec;
displayScore.innerHTML = format(presents) + " Presents delivered.";
totalPresentsDisp.innerHTML = format(totalPresents) + " Total presents delivered";
title.innerHTML = format(presents) + " Presents";
}
I am making a food delivery app. I would like that there would be a place whereby it would display the total. Right now, I am unable to display the total amount from multiplying quantity and price. It does not show up on the app.
And, there are no errors on the console too.
Javascript Code:
function _showorderResult(arr) {
var value1 = arr[0].price;
var value2 = arr[0].quantity;
for (var i = 0; i < arr.length; i++) {
result = value1 * value2;
htmlstring = "";
$("#itemimage").html("<img src='" + serverURL() + "/images/" +
arr[i].imagefile + "' width='200'>");
$("#price").html("Price" + ": " + " $" + arr[i].price);
$("#itemname").html("Item" + ":" + arr[i].itemName);
$("#quantity").html("Quanitiy" + ":" + arr[i].quantity);
$("result").append(htmlstring);
$("#requestedDateTime").html("To delivery by" + ":" + arr[i].requestedDateTime);
$("#deliveredDateTime").html("Delivered on" + ":" + arr[i].deliveredDateTime)
}
}
And, there are no errors on the console too.
There were plenty of errors in my console, but there are several mistakes here. The first is that your code is not runnable. Please consider making a minimal, verifiable example.
Next, you are misusing or not properly formatting the append(...) function. That's intended to append HTML elements, not string values.
As the comments suggest, you seem to have confused var result and $("result"). If you're not using the DOM selector, you probably don't want to jQuery-wrap your variables. The proper jQuery-wrap syntax would have been $(result) without the double quotes, but please don't do that either, it doesn't offer any benefit over just var result. htmlstring doesn't contain any actual HTML, so I've renamed it runningTotal instead and add it to the price * quantity. This must be initialized first or you'll get NaN.
Make sure to initialize your variables. To this point, there's some hard-coded indexes such as value1 = arr[0].price which make no sense in this pasted code. We can assume you left these here after troubleshooting. Please clean them up next time.
Finally, this is minor, but be consistent with your object names... e.g. imagefile versus imageFile. It doesn't matter which you choose so as long as you're consistent. This will help find typos down the road.
Here's a working example:
<html>
<img src="" id="itemimage">
<p id="price">Price: $0.00</p>
<p id="itemname">Item: None</p>
<p id="quantity">Quantity: None</p>
<p id="result">Running: None</p>
<p id="requestedDateTime">To delivery by: None</p>
<p id="deliveredDateTime">Delivered on: None</p>
<script>
var order = [{
price: 5,
quantity: 3,
itemName: 'Pizza',
imagefile: 'pizza.png',
requestedDateTime: '12:00',
deliveredDateTime: '12:30'
}];
/** Dummy function to allow code to run **/
var serverURL = function() { return ""; }
function _showorderResult(arr) {
// var value1 = arr[0].price;
// var value2 = arr[0].quantity;
var result;
var runningTotal = 0;
for (var i = 0; i < arr.length; i++) {
result = arr[i].price * arr[i].quantity;
runningTotal += result;
$("#itemimage").html("<img src='" + serverURL() + "/images/" + arr[i].imagefile + "' width='200'>");
$("#price").html("Price" + ": " + " $" + arr[i].price);
$("#itemname").html("Item" + ":" + arr[i].itemName);
$("#quantity").html("Quanitiy" + ":" + arr[i].quantity);
$("#result").html("Running" + ":" + runningTotal);
$("#requestedDateTime").html("To delivery by" + ":" + arr[i].requestedDateTime);
$("#deliveredDateTime").html("Delivered on" + ":" + arr[i].deliveredDateTime);
}
}
_showorderResult(order);
</script>
</html>
Hopefully this is the correct place to ask this question. I'm pretty much brand new to javascript, but seeing it's similarities to the other languages I write in, it's been pretty easy so far- until now.
I'm writing a script for a button that is clicked when a user is done filling out a grid. The script goes through the fields in the grid, grabs the information, and generates an email. It then sends out a mailto: command with the information that was generated, much easier than the user having to type the email themselves. The problem I'm having is that one of the criteria for a field is a Tax ID, which can sometimes start with a zero, and when I go to assign that field value to a variable, it drops the leading zero. How do I get javascript to keep this leading zero? I've tried declaring a variable with a " " at the beginning to try to force it to recognize the variable as a string, but that doesn't seem to work.
Here's my code:
if(this.getField("ProviderOne").value != "")
{
// This is the form return email. Its hardcoded
// so that the form is always returned to the same address
var cToAddr = "blank#blank.org";
// First, get the client CC email address
var cCCAddr = "blank#blank.com";
var pOneTaxID = new String(this.getField("ProviderOneTaxID").value); //tring to force string value
// Set the subject and body text for the email message
var ProviderOne = this.getField("ProviderOne").value + " NPI:" + this.getField("ProviderOneNPI").value + " Tax ID:" + pOneTaxID;
var ProviderTwo = this.getField("ProviderTwo").value + " NPI:" + this.getField("ProviderTwoNPI").value + " Tax ID:" + this.getField("ProviderTwoTaxID").value;
var ProviderThree = this.getField("ProviderThree").value + " NPI:" + this.getField("ProviderThreeNPI").value + " Tax ID:" + this.getField("ProviderThreeTaxID").value;
var ProviderFour = this.getField("ProviderFour").value + " NPI:" + this.getField("ProviderFourNPI").value + " Tax ID:" + this.getField("ProviderFourTaxID").value;
var ProviderFive = this.getField("ProviderFive").value + " NPI:" + this.getField("ProviderFiveNPI").value + " Tax ID:" + this.getField("ProviderFiveTaxID").value;
var cSubLine = this.getField("ProviderOne").value + " ERA setup for [BLANK]";
var cBody = "To [BLANK], \n \nPlease enroll the following providers to receive [BLANK] through [BLANK] under [BLANK]: \n \n";
if(this.getField("ProviderOne").value != "")
cBody += "1. " + ProviderOne + "\n";
if(this.getField("ProviderTwo").value != "")
cBody += "2. " + ProviderTwo + "\n";
if(this.getField("ProviderThree").value != "")
cBody += "3. " + ProviderThree + "\n";
if(this.getField("ProviderFour").value != "")
cBody += "4. " + ProviderFour + "\n";
if(this.getField("ProviderFive").value != "")
cBody += "4. " + ProviderFive + "\n";
cBody += "\n Thank you,\n" + this.getField("ProviderOne").value;
app.mailMsg({bUI: true, cTo: cToAddr, cCc: cCCAddr, cBCc: "", cSubject: cSubLine, cMsg: cBody});
}
else
{
app.alert("Please enter at least one payer into the grid above.", 1, 0, "Unfilled Form");
this.getField("ProviderOne").setFocus();
}
Thanks a ton for taking the time to read through this, and even more thanks to you if you can help me find a solution.
-Andrew
Figured it out. Instead of grabbing the value using getField("FieldName").value, I grabbed it using .valueAsString. Hopefully this is useful if someone finds it down the road.
I built a page that uses a simple JSon table and JS/JQ to present that data. Hosted together on one sheet it works fine in both Chrome and FF. Split into seperate HTML, CSS, JS and JSON files, however, there is a slightly variable bug in Chrome.
Page: http://www.lafairclough.co.uk/JTest/index.html
Select two options from the drop down and the charts on the right should show the relative performance data from two cars (top to bottom: 0-60, 0-100, Standing Qtr and Top Speed). These are colour coded with green being the faster result and orange denoting a draw for a given variable.
The charts are made using Java to calculate and set a CSS div width. In Chrome, however, this div width is (sometimes, but often) getting calculated as a much higher figured than expected. As flows:
// Perf. BAR CHART SIZE CSS CAR A
$.getJSON("cars.json", function (data) {
$(document).ready(function () {
$('#dropdown1').change(function () {
var index = parseInt($(this).val()),
html = "<p class=\"barText\">" + " " + data.carList[index].model + " " + data.carList[index].variant + "</p>";
$(".carA060").html(html);
var index = parseInt($(this).val());
var num = data.carList[index].zero60 * 10;
$(".carA060").css('width', num + '%').show();
html = "<p class=\"barText\">" + " " + data.carList[index].model + " " + data.carList[index].variant + "</p>";
$(".carA0100").html(html);
var index = parseInt($(this).val());
var num = data.carList[index].zero100 * 5;
$(".carA0100").css('width', num + '%').show();
html = "<p class=\"barText\">" + " " + data.carList[index].model + " " + data.carList[index].variant + "</p>";
$(".carAsQTR").html(html);
var index = parseInt($(this).val());
var num = data.carList[index].sQTR * 5;
$(".carAsQTR").css('width', num + '%').show();
html = "<p class=\"barText\">" + " " + data.carList[index].model + " " + data.carList[index].variant + "</p>";
$(".carAvMAX").html(html);
var index = parseInt($(this).val());
var num = data.carList[index].vMAX * 0.5;
$(".carAvMAX").css('width', num + '%').show();
});
});
});
Any idea as to why it's going awry in Chrome would be hugely appreciated.
Thanks,
Lee.
your are passing 14.6 ( the mazda ) in your json and multiplying it by 10 for the width so thats why you are
out of bound of container change the logic of the calculation of the width and you will be fine. and the reason why in fire fox its ok and chrome not is because each browser parse the CSS differently . hope this helped
My code won't run when I try to display more than one variable in the document.write section of the code. I'm pretty sure I was doing everything right.
<script type="text/javascript">
var name = prompt("Welcome to the Fruity Store. What is your name?","");
var product = prompt("What is the name of the product you would like?","");
var price = 1*prompt("How much does it cost?","");
var quantity = 1*prompt("How many of the fruit would you like?","");
var discount = 1*prompt("What was the discount of the product in decimal form?","");
var costoforder = (price*quantity);
var discounted = (price*quantity*discount);
var totalorder = (costoforder - discounted);
document.write("Thank you for placing an order with us " +name )
document.write("<p>The cost of buying " +quantity "of " +product "is " +costoforder </p>)
document.write("<p>The discount for this purchase is " +discounted </p>)
document.write("<p>With discount, your total order cost is " +totalorder</p>)
</script>
You are missing some plus signs in your string concatenation.
"<p>The cost of buying " + quantity + " of " + product + " is " + etc.
You are missing "+" signs after your variables.
You put
"String" + variable "string"
Instead of
"string" + variable + "string"
Several times in your document.write statements
You need to use the plus sign, +, for string concatenation. Also you are missing the ; after the statements.
<script type="text/javascript">
var name = prompt("Welcome to the Fruity Store. What is your name?","");
var product = prompt("What is the name of the product you would like?","");
var price = 1*prompt("How much does it cost?","");
var quantity = 1*prompt("How many of the fruit would you like?","");
var discount = 1*prompt("What was the discount of the product in decimal form?","");
var costoforder = (price*quantity);
var discounted = (price*quantity*discount);
var totalorder = (costoforder - discounted);
document.write("Thank you for placing an order with us " + name );
document.write("<p>The cost of buying " + quantity + "of " + product + "is " + costoforder + "</p>");
document.write("<p>The discount for this purchase is " + discounted + "</p>");
document.write("<p>With discount, your total order cost is " +totalorder + "</p>");
</script>