I am basing this code off of this jsfiddle:
http://jsfiddle.net/vxupE/
I would love to implement these price levels into my code so that when a person puts in $501 they are charged 20% but if they put in $500 they are charged 25%
if $price =< 101 then *.30
if $price > 100 and < 501 then *.25
if $price > 500 and < 1501 then *.20
if $price > 1500 then *.15
I'm at a loss when is comes to javascript. I think this could help others though. Would definitely help me! :)
Try this:
$('#sub_tot').change(function(){
var value = $(this).val();
var charge = 0;
if ( value >= 501 ) {
charge = .25;
}
else if ( value >= 100 ) {
charge = .20;
}
$('#tax').val( (value * charge).toFixed(2) );
}).change()
There are two ways I would consider.
switch statements, there are plenty of tutorials on line to look through. The other option is is using if and else if To find the correct additional charge.
if($price =< 101){
charge=0.3;
}else if($price>=100){
charge=0.25;
}else if($price>=500){
charge=0.2;
}else if($price>=1500){
charge=0.15;
where charge can then be used to calculate the final cost.
UPDATE
your code is checking if your sub total value is equal to your zip code. change
$('#sub_tot').change(function(){ to $('#zip').change(function(){ to
Related
I’m making a page to track the quantity/value of 8 sets of assets.
Each Asset will have several buttons that do the same thing just for different Variables depending on the asset that triggers them.
I’m wondering if there is a way to set the variables when it’s triggered or do O just have to copy-paste and edit each function 8 times?
Here is the code I’m starting with it adds A quantity of the asset and removes the cost from the cash value
function buya() {
var quant = document.getElementById("input").value;
quant = Number(quant)
var cost = document.getElementById("a3").innerHTML;
var cash = document.getElementById("cash").innerHTML;
cash = Number(cash)
cost = Number(cost)
var a4 = document.getElementById("a4").innerHTML;
a4 = Number(a4)
console.log(a4)
console.log(quant)
if (cash > cost) {
cash = cash - cost;
a4 += quant;
document.getElementById("cash").innerHTML = cash;
document.getElementById("a4").innerHTML = a4;
} else
alert("you don't have enough money to buy those shares")
}
Basically I want to swap most all of the variables a3, a4 into b2,b4 variables
——edit—— Okay I think I have a fix but it’s clumsy and better ones would be appreciated.
First Add a drop-down to select which asset then replace the things I want to shift with blank variables m, say cuz then at the start of the function add an 8 pronged if/else statement assigning field locations to those variables based on the drop-down selection.
Hate it when the answer pops into my head 5 minutes after posting
——edit ends——
Use function parameters, and then bind event listeners to functions that call it with different parameters.
function buya(costid, a4id) {
var quant = document.getElementById("input").value;
quant = Number(quant)
var cost = document.getElementById(costid).innerHTML;
var cash = document.getElementById("cash").innerHTML;
cash = Number(cash)
cost = Number(cost)
var a4 = document.getElementById(a4id).innerHTML;
a4 = Number(a4)
console.log(a4)
console.log(quant)
if (cash > cost) {
cash = cash - cost;
a4 += quant;
document.getElementById("cash").innerHTML = cash;
document.getElementById(a4id).innerHTML = a4;
} else
alert("you don't have enough money to buy those shares")
}
someElement.addEventListener("click", () => buya("a3", "a4"));
otherElement.addEventListener("click", () => buya("b2", "b4"));
We can pass elements as parameters to the function
function buya(ele1, ele2){
console.log(ele1.innerHTML);
console.log(ele2.innerHTML);
}
<div id="a3">I am a3</div>
<div id="a4">I am a4</div>
<div id="b3">I am b3</div>
<div id="b4">I am b4</div>
<button onClick="buya(document.getElementById('a3'), document.getElementById('a4'));">Click for A3 and A4</button>
<button onClick="buya(document.getElementById('b3'), document.getElementById('b4'));">Click for B3, B4</button>
I have a food ordering script which I want to add If delivery time is between 8:00:00PM - 7:59:59AM to add an extra fee of $5 and if it is between 8:00:00 AM and 7:59:59 PM to keep delivery as is in the script.
This is my code that calculates the delivery fee that returns the delivery fee we already have set in our dashboard.
We want to add this as a fix to add a fee for our night deliveries.
Day deliveries = Normal delivery Fee
Night Delivery = Normal delivery fee + 5
Thank you and I hope someone can guide me.
public static function verifyLocation($merchant_id=0, $lat=0, $lng=0,$order_subtotal=0)
{
$resp = Yii::app()->db->createCommand()
->select('merchant_id,latitude,lontitude,minimum_order')
->from('{{merchant}}')
->where("merchant_id=:merchant_id",array(
':merchant_id'=>(integer)$merchant_id,
))
->limit(1)
->queryRow();
if($resp){
$provider = FunctionsV3::getMapProvider();
MapsWrapper::init($provider);
$unit = FunctionsV3::getMerchantDistanceType($merchant_id);
$mode = isset($provider['mode'])?$provider['mode']:'driving';
$merchant_delivery_distance = getOption($merchant_id,'merchant_delivery_miles');
/*GET DELIVERY FEE*/
$delivery_fee = getOption($merchant_id,'merchant_delivery_charges');
$resp_distance = array();
if($merchant_delivery_distance>0){
$resp_distance = MapsWrapper::getDistance($resp['latitude'],$resp['lontitude'],$lat,$lng,$unit,$mode);
$distance = $resp_distance['distance'];
if($merchant_delivery_distance>0){
if($distance>$merchant_delivery_distance){
$pretty_distance = Yii::t("default","[distance] [unit]",array(
'[distance]'=>$merchant_delivery_distance,
'[unit]'=>MapsWrapper::prettyUnit($unit)
));
$error = Yii::t("default","Sorry but this merchant delivers only with in [distance] your current distance is [current_distance]",array(
'[distance]'=>$pretty_distance,
'[current_distance]'=>$resp_distance['pretty_distance']
));
throw new Exception( $error );
}
}
/*MINIMUM ORDER TABLE*/
$min_tables_enabled = getOption($merchant_id,'min_tables_enabled');
if($min_tables_enabled==1){
$min_order = self::getMinimumOrderTable(
$merchant_id,$resp_distance['distance'],$resp_distance['unit'],$resp['minimum_order']
);
if($min_order>$order_subtotal){
$error = Yii::t("default","Sorry but minimum order is [min_order] for distance [distance]",array(
'[min_order]'=>FunctionsV3::prettyPrice($min_order),
'[distance]'=>$resp_distance['pretty_distance']
));
throw new Exception( $error );
}
}
/*SHIPPING FEE*/
$shipping_enabled = getOption($merchant_id,'shipping_enabled');
if($shipping_enabled==2){
$delivery_fee = self::getShippingFee($merchant_id,$resp_distance['distance'],$resp_distance['unit'],$delivery_fee);
}
}
return array_merge((array)$resp_distance, array('delivery_fee'=>$delivery_fee));
} else throw new Exception( t("Merchant not found") );
}
You could achieve that by using php date to get time between desired time so you can increase the fee accordingly
*Note : PHP gets date from server ,if you were to set the price based on the individual user timezone.Javascript should be used to integrate with PHP
<?php
date_default_timezone_set('Africa/Johannesburg'); //Set your timezone here get php timezone from
https://www.php.net/manual/en/timezones.php
$normalfee = "500"; //The variable containing the normal fee
$tax = "5"; //The added tax for after 8pm fee increase
$getdate = date("Hi"); //Get some time from the server
echo $getdate."Debug : The current time now<br>"; //For debug purposes
if(($getdate > "759") && ($getdate < "2000")){
$finalfee = $normalfee;
echo $finalfee."Debug : Still the same fee<br>"; //The fee should remain normal starting at 8:00am till 7:59:59pm
} else {
$finalfee = $normalfee + $tax;
echo $finalfee."Night time fee added<br>"; //The fee will increase by 5 starting from 8:00pm till 7:59:59am
}
echo "Debug variable passed out of condition the dollar sign can now be added $".$finalfee."<br>";
//Again Debugging this is to show you can then use the $finalfee variable outside the conditions
?>
The script cleaned up...
<?php
date_default_timezone_set('Africa/Johannesburg');
$normalfee = "500";
$tax = "5";
$getdate = date("Hi");
if(($getdate > "759") && ($getdate < "2000")){
$finalfee = $normalfee;
} else {
$finalfee = $normalfee + $tax;
}
$display = "Final price $".$finalfee;
?>
And how do I get it to display the number, not undefined?
It's a tipping app. The user inputs the price of whatever it is they bought (pizza, haircut, etc.) in #price, then calcTip() calculates the tip, sends it over to calcTotal() which calculates the total, and sends it over to displayAmounts().
I don't know exactly what happens, but something messes up with the variable tip. calcTip() works correctly and calculates the tip amount successfully. I know this because the JavaScript console displays the amount when I input tip;. However, on the page, #tipSpan displays the tip as undefined.
What baffles me most is that the variable total works perfectly fine.
Does anyone know what might be going on or how I can fix it?
Here is the HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Tipping App</title>
<style>
<!-- Temporary -->
#error {
display: none;
}
</style>
</head>
<body>
<div id="wrapper">
<header>
<h1>Tipping App</h1>
</header>
<section>
<div class="price">
<h2>Price Information</h2>
<label for="priceInput">Enter the price below!</label><input id="priceInput" type="text"><button id="calcButton">Calculate the Tip</button>
<p id="error">Error: You need to enter the cost!<br><br>Use only numbers and decimal points, no currency symbols or letters.</p>
</div>
<div id="tipContainer" class="tip">
<h2>Tip Information</h2>
<p id="tipPara">Your tip should be... <span>$<span id="tipSpan"></span></span></p>
</div>
<div id="totalContainer" class="total">
<h2>Total Information</h2>
<p id="totalPara">Your total is... <span>$<span id="totalSpan"></span></span></p>
</div>
</section>
</div>
<script src="js/app.js"></script>
</body>
</html>
Here is the JavaScript:
///// VARIABLES
//////////////////////////////
var priceInput = document.getElementById("priceInput");
var calcButton = document.getElementById("calcButton");
var error = document.getElementById("error");
var tipContainer = document.getElementById("tipContainer");
var tipPara = document.getElementById("tipPara");
var tipSpan = document.getElementById("tipSpan");
var totalContainer = document.getElementById("totalContainer");
var totalPara = document.getElementById("totalPara");
var totalSpan = document.getElementById("totalSpan");
var tip;
var total;
///// FUNCTIONS
//////////////////////////////
function calcTip() {
var price = priceInput.value; // This is the price the user inputs
var minTip = (Math.ceil(price * .15)); // Calculates a 15% tip rounded up to the nearest dollar
var maxTip = (price * .2); // Calculates a 20% tip
if (isNaN(price) || price === "") {
// If the user doesn't enter a number
// Or doesn't enter anything,
// Then display the error message
error.style.display = "block";
return;
} else {
error.style.display = "none";
if (maxTip < minTip) {
// If the 20% tip is less than the 15% rounded tip,
// Then let's go with that 20% tip
calcTotal(price, maxTip);
tip = maxTip;
} else {
// Otherwise, let's just do the 15%
calcTotal(price, minTip);
tip = minTip;
};
};
};
function calcTotal(price, tip) {
// Add the price and the tip together to yield the total
price = parseInt(price);
tip = parseInt(tip);
total = (price + tip);
displayAmounts();
}
function displayAmounts() {
// Update the page to display the tip and the total to the user
tipContainer.style.display = "block";
totalContainer.style.display = "block";
tipSpan.innerText = tip;
totalSpan.innerText = total;
}
///// EVENTS
//////////////////////////////
calcButton.addEventListener("click", calcTip);
Also, unrelated, but does my JavaScript look good? Is it clean code? I hope to find a web development job in the near future, and I know I need to be good at JavaScript.
WORKING DEMO
Update the function arguments
function calcTotal(price, maxTip) {
// Add the price and the tip together to yield the total
price = parseInt(price);
tip = parseInt(maxTip);
total = (price + tip);
displayAmounts();
}
Here the argument tip is overriding the global variable. Replace it to maxTip as you call.
1) In function displayAmounts, pass parameters tip & total
2) Instead of
tipSpan.innerText = tip,
TRY WITH
tipSpan.innerHTML = tip;
and same for total ,
use totalSpan.innerHTML = total
instead of
totalSpan.innerText ;
Then it should work
Try changing your method definition so it passes the values in:
displayAmounts(); should become displayAmounts(tip, total);
See the fiddle here.
Also you should use parseFloat rather than parseInt assuming you'll want to be more accurate than whole numbers.
Just a small mistake!
Instead of:
calcTotal(price, minTip);
tip = minTip;
Do:
tip = minTip;
calcTotal(price, minTip);
This way tip is calculated before displayAmounts is run.
Abut your code:
This is fine with just getting started. I recommend going through w3school's tutorials on javascript. The more you use javascript, the better you will get.
If you want a learning path I would recommend taking, let me know.
innerText works only on IE. textContent is W3C-compliant, but if you want your code to be standards compliant and cross-browser safe you should use this:
while( tipSpan.firstChild ) {
tipSpan.removeChild( tipSpan.firstChild );
}
tipSpan.appendChild( document.createTextNode(tip) );
Do this for totalSpan also.
Well, my code have been working fine and I'm simply trying to make a simple game, until I added this (due to that I wanted to learn how to save the info to the users local storage):
if(localStorage.getItem('money'))
{
var Money = localStorage.getItem('money');
document.getElementById('test').innerHTML="EXISTS";
} else {
localStorage.setItem('money', 0);
var Money = localStorage.getItem('money');
document.getElementById('test').innerHTML="DOES NOT EXIST";
}
My full code looks like this:
<head><meta charset="UTF-8"></head>
<body><span id='test'></span>
Generated something: <span id='money'>0$</span> (money per click: <span id='MPC'>1$</span>)
<br />
Upgrade 1 upgrades: <span id='u1Us'>0</span> (production rate: <span id='u1Pr'>0</span>)
<br />
<span id='updates'></span>
<br />
<button onClick='mButton()'>Generate something.</button>
<br /><br />
<b>Upgrades:</b>
<br /><br />Generator upgrades:<br />
<button onClick='buyU1()'>Buy upgrade 1. ($30)</button>
<br /><br />Self-generated upgrades:<br />
<button onClick='buySG1()'>Buy Self-Generated Upgrade 1 ($500)</button>
</body>
<script>
if(localStorage.getItem('money'))
{
var Money = localStorage.getItem('money');
document.getElementById('test').innerHTML="EXISTS";
} else {
localStorage.setItem('money', 0);
var Money = localStorage.getItem('money');
document.getElementById('test').innerHTML="DOES NOT EXIST";
}
var U1Amount = 0;
var cMoney = 1;
function mButton()
{
Money += cMoney;
document.getElementById('money').innerHTML=Money + "$";
}
function buyU1()
{
if(Money < 30)
{
document.getElementById('updates').innerHTML="You do not have enough money.";
resetUpdates();
} else {
Money -= 30;
U1Amount += 1;
document.getElementById('u1Us').innerHTML=U1Amount;
document.getElementById('money').innerHTML=Money + "$";
document.getElementById('updates').innerHTML="You have successfully bought Upgrade 1";
var calcU1Amount = U1Amount * 5;
document.getElementById('u1Pr').innerHTML=calcU1Amount;
resetUpdates();
}
}
var interval = setInterval(gMoneyU1, 1000);
function gMoneyU1()
{
var calc = 5 * U1Amount;
Money += calc;
document.getElementById('money').innerHTML=Money + "$";
}
function buySG1()
{
if(Money < 500)
{
document.getElementById('updates').innerHTML="You do not have enough money.";
resetUpdates();
} else {
Money -= 500;
cMoney += 1;
document.getElementById('MPC').innerHTML=cMoney + "$";
document.getElementById('money').innerHTML=Money;
}
}
function resetUpdates()
{
setTimeout(function(){document.getElementById('updates').innerHTML="";}, 10000);
}
</script>
I'm going to add the localStorage to all info that I want to save, but I'm having problems with the first one so yer.
What my code WITH my save-the-persons-info outputs is: http://puu.sh/6iONl.png (and it keeps on in all eternally)
It keeps adding '0' for some reason and I can't figure out why. I'd really appreciate help.
Thanks in advance.
Sorry if my code is messy, I'm still learning, hence why asking for help.
The only time that you ever set to localStorage is when you call localStorage.setItem('money', 0);.
You probably want to change that to setting the real value of the money variable.
Local storage stores everything as a string, so you'll want to call parseInt() on whatever you get back from local storage. Then, you should be able to properly add two ints together, rather than concatenating two strings together.
The values in localStorage are all strings. When you do:
localStorage.setItem('x', 0);
var x = localStorage.getItem('x'); // x === '0'
x = x + 1; // x = '01';
the thing you set in local storage will be the value you gave converted to a string. You should parseInt (or convert it some other way back to a number) when you retrieve it from localStorage to avoid this problem.
Your if statement will always return false so you'll never get to the "if true" part of your if statement. This is because the local storage value will either be null if not set, or a string value ("0") on most browsers if set, or an integer on some browsers if set. (Most browsers will only maintain strings for local storage, although the HTML5 specs do allow for other values.)
So first, of you would need to change the if part to something like this:
if (localStorage.getItem('money') != null)
I'm not completely sure what you're trying to achieve logic-wise but as mentioned, your other issue is that you're only setting the value to 0 and then reading the value right after (which would be zero still.) This is why you're getting zeros.
How do I modify PrestaShop 1.5 to display product prices in two currencies at the same time (ie. base currenct and visitor's currency on products listed in product & categories pages):
I think I should be modifying ProductController.php and product.tpl. Is this correct?
Below is one solution for the product page that I find on a forum, but it is for PrestaShop 1.4x:
Override ProductController.php in /controllers/ProductController.php
<?php
class ProductController extends ProductControllerCore{
public function displayContent() {
global $currency;
$second_currency = 'USD';
$productPriceWithTax = Product::getPriceStatic($this->product->id, true, NULL, 6);
if (Product::$_taxCalculationMethod == PS_TAX_INC) {
$productPriceWithTax = Tools::ps_round($productPriceWithTax, 2);
}
$productPriceWithoutEcoTax = (float)($productPriceWithTax - $this->product->ecotax);
$current_currency = $currency->iso_code;
$default_currency = Currency::getDefaultCurrency()->iso_code;
$currency_array = Currency::getCurrencies($object = false, $active = 1);
if ($current_currency == $default_currency) {
foreach ($currency_array as $arr) {
if ((string)$arr['iso_code'] == $second_currency) {
$second_currency_price = Tools::ps_round($productPriceWithoutEcoTax * (float)$arr['conversion_rate'], 2);
}
}
}
self::$smarty->assign('second_currency_price', $second_currency_price . ' ' . $second_currency);
parent::displayContent();
}
}
Modify product.tpl:
{if $priceDisplay >= 0 && $priceDisplay <= 2}
<span id="our_price_display">{convertPrice price=$productPrice}</span>
to
{if $priceDisplay >= 0 && $priceDisplay <= 2}
{$second_currency_price} /
<span id="our_price_display">{convertPrice price=$productPrice}</span>
In above example USD is the second currency ($second_currency='USD'). I was wondering if it would be possible to modify this code for PrestaShop 1.5, which has changed significantly since 1.4x.
You have to loop this array which contains all the currencies you manage: {$currencies}
{foreach from=$currencies item=c}{$c.name}{/foreach}
The default currency is in: {$id_currency_cookie}
If I remember, you have to write this in product.tpl.
I don't know how to display the correct price for your currency. Tell us if you find.