Calculating unit price based on quantity entered - javascript

I'm trying to create a script that displays a price in one box based on the number of employees entered in an adjacent box.
The script works fine for a static amount, i.e. the base price is £8 per employee. If 5 is entered the price displayed is correct, £40.
The problem I'm having is changing the unit price when a certain threshold is met. The unit price for 1-5 employees is 8, 6-21 is 7 and 22-50 is 6.
No matter what is entered in the employee box, the number is always multiplied by 8.
I'm very inexperienced when it comes to javascript so any help will be very welcome!
Here is my code:
<div class="employee-button">
<form name="calculator" id="calculator">
<input name="employees" id="employees" type="text" placeholder="# of Employees" />
</form>
</div>
<div class="cost-button">
<span id="result">Monthly Cost</span>
</div>
Javascript
$(function() {
var ccNum;
$('#employees').keyup(function(){
ccNum = $(this).val();
});
if((ccNum >= 0) && (ccNum <= 5)){
var unitPrice = 8
}
else if((ccNum >= 6) && (ccNum <= 21)){
var unitPrice = 7
}
else if((ccNum >= 21) && (ccNum <= 50)){
var unitPrice = 6
}
else var unitPrice = 8;
$('#employees').keyup(function(){
$('#result').text(ccNum * unitPrice);
});
})

Put everything within the keyup function. Your code wasn't working because the logic to calculate the price is only executed once, not for every keyup event.
$('#employees').keyup(function(){
var ccNum = $(this).val();
if((ccNum >= 0) && (ccNum <= 5)){
var unitPrice = 8
}
else if((ccNum >= 6) && (ccNum <= 21)){
var unitPrice = 7
}
else if((ccNum >= 21) && (ccNum <= 50)){
var unitPrice = 6
}
else var unitPrice = 8;
$('#result').text(ccNum * unitPrice);
});

In addition to putting the code inside your event handler, you do not need to keep declaring the same variable over and over. Also the test for 0 to 5 is not needed (as already covered by the default value):
$('#employees').keyup(function(){
var ccNum = ~~$(this).val();
// Start with the default
var unitPrice = 8;
if((ccNum >= 6) && (ccNum <= 21)){
unitPrice = 7;
}
else if((ccNum >= 21) && (ccNum <= 50)){
unitPrice = 6;
}
$('#result').text(ccNum * unitPrice);
});
Note: ~~ is a shortcut conversion to an integer value.

Related

Simplifying multiple similar If statements (JAVASCRIPT)

Im working on a code for an adobe acrobat form, I want to add the following code:
var total =6301
var warranty
if (0 < total && total <= 3300){warranty = 194.25}
else if (3300 < total && total <= 4000){warranty = 197.5}
else if (4000 < total && total <= 5000){warranty = 202.15}
else if (5000 < total && total <= 6000){warranty = 206.75}
else if (6000 < total && total <= 7000){warranty = 211.45}
else if (7000 < total && total <= 8000){warranty = 216.1}
else if (8000 < total && total <= 9000){warranty = 220.75}
else if (9000 < total && total <= 10000){warranty = 225.4}
else if (10000 < total && total <= 11000){warranty = 230.1}
else if (11000 < total && total <= 12000){warranty = 234.75}
else if (12000 < total && total <= 13000){warranty = 239.4}
else if (13000 < total && total <= 14000){warranty = 243.95}
else if (14000 < total && total <= 15000){warranty = 248.7}
else if (15000 < total && total <= 16000){warranty = 253.3}
else if (16000 < total && total <= 17000){warranty = 258}
else if (17000 < total && total <= 18000){warranty = 262.65}
else if (18000 < total && total <= 19000){warranty = 267.3}
else if (19000 < total && total <= 20000){warranty = 271.95}
else if (20000 < total && total <= 21000){warranty = 276.6}
else if (21000 < total && total <= 22000){warranty = 281.3}
else if (22000 < total && total <= 23000){warranty = 285.9}
else if (23000 < total && total <= 24000){warranty = 290.5}
else if (24000 < total && total <= 25000){warranty = 295.25}
else if (25000 < total && total <= 26000){warranty = 299.85}
else if (26000 < total && total <= 27000){warranty = 304.55}
else if (27000 < total && total <= 28000){warranty = 309.15}
else if (28000 < total && total <= 29000){warranty = 313.85}
else {warranty = 999999}
I want to have this be a lot less repetitive as I have a lot more conditions similar to the ones above.
Thanks for the help in advance!!
This approach features an array with value pairs which works for any values.
const
getValue = total => [
[3300, 194.25], [4000, 197.5], [5000, 202.15], [6000, 206.75],
[7000, 211.45], [8000, 216.1], [9000, 220.75], [10000, 225.4],
[11000, 230.1], [12000, 234.75], [13000, 239.4], [14000, 243.95],
[15000, 248.7], [16000, 253.3], [17000, 258], [18000, 262.65],
[19000, 267.3], [20000, 271.95], [21000, 276.6], [22000, 281.3],
[23000, 285.9], [24000, 290.5], [25000, 295.25], [26000, 299.85],
[27000, 304.55], [28000, 309.15], [29000, 313.85], [Infinity, 999999]
].find(([t]) => total <= t)[1];
console.log([0, 1, 3300, 3500, 3999, 4000, 4001, 5000, 10000, 100000].map(getValue));
Use switch case instead which is ideal in terms of optimisation & performance. This way the code execution directly jumps into the corresponding condition rather than going through each if else if condition.
var total = 6301;
var warranty;
switch (true) {
case (0 < total && total <= 3300): warranty = 194.25; break;
case (3300 < total && total <= 4000): warranty = 194.25; break;
...
default: warranty = 999999; break;
}

Recursively setting a value depending on range using JavaScript

I don't know how to word this but this is what I'm trying to do:
if (score >= 0 && score <= 10) overallScore = 0;
else if (score >= 11 && score <= 20) overallScore = 1;
else if (score >= 21 && score <= 30) overallScore = 2;
else if (score >= 31 && score <= 40) overallScore = 3;
else if (score >= 91 && score <= 100) overallScore = 9;
...
Is there any way to recursively do this using a function?
overallScore = Math.max(0, Math.floor((score - 1) / 10));
no need for recursion. But if you need that:
const getOverall = score => score <= 10 ? 0 : getOverall(score - 10) + 1;
Recursion is not really appropriate here, since you can get the required value in constant time. Recursion becomes interesting when you need at least O(logn) time.
But as you ask for it, here is one way to make it recursive:
function range(score, depth = 0) {
return score <= 10 || depth >= 9 ? 0 : range(score-10, depth+1) + 1;
}
console.log(range(0)); // 0
console.log(range(10)); // 0
console.log(range(11)); // 1
console.log(range(60)); // 5
console.log(range(91)); // 9
console.log(range(110)); // 9

Calculator Script or Plugin

I'm looking for the Calculator Plugin (for Wordpress) or Script which should work in such a way:
Should be only one field where user can type the number of my product (Instagram Likes). And depending on the number the cost changes.
I'v got the variety of prices for different Likes number. For example:
1-10000 likes = 0,0009 per 1 like
10001-50000 = 0,0008 per 1 like etc
And if the user type the number 5555 it should automatically count 5555*0.0009
Could you, please, help me?
var likes = document.getElementById("your id for likes").value;
var costPerLike;
if(likes <= 10000){costPerLike = 0.0009} else if(likes >= 10001 && likes <= 50000){costPerLike = 0.0008}
i think this should help you get in the right direction.
you probably want this in an onchange or onsubmit event.
You can use this one.
function priceCalculation(a){
if(a <= 10000){
return 0.0009;
}else if(a >= 10001 && a <= 25000 ){
return 0.0008;
}else if(a >= 25001 && a <= 50000 ){
return 0.0007;
}else if(a >= 50001 && a <= 100000 ){
return 0.0005;
}else{
return 0.0004;
}
}
$('#likecount').keyup(function(){
var price = priceCalculation($(this).val());
console.log(price)
var total = $(this).val() * price;
$('#output').text(total.toFixed(4));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="likecount" />
<p>Price: <span id="output"></span></p>

Error in JavaScript return code?

Here is the javascript code:
There is an error in code where nightSurcharges is added to total cost even if pickUptime is less than 20.
function TaxiFare() {
var baseFare = 2;
var costPerMile = 0.50;
var nightSurcharge = 0.50; // 8pm to 6am, every night //its flat 0.50 and not per mile
var milesTravelled = Number(document.getElementById("miles").value) || 0;
if ((milesTravelled < 1) || (milesTravelled > 200)) {
alert("You must enter 1 - 200 miles");
document.getElementById("miles").focus();
return false;
}
var pickupTime = Number(document.getElementById("putime").value) || 0;
if ((pickupTime == "") || (pickupTime < 0) || (pickupTime > 23)) {
alert("The time must be 0-23 hours");
document.getElementById("putime").focus();
return false;
}
var cost = baseFare + (costPerMile * milesTravelled);
// add the nightSurcharge to the cost if it is after
// 8pm or before 6am
if (pickupTime >= 20 || pickupTime < 6) {
cost += nightSurcharge;
}
alert("Your taxi fare is $" + cost.toFixed(2));
}
I want nightSurcharge to be added only when pickupTime is >=20, but that's not working right now.
Any help is appreciated. Thanks
This seems obvious to me.
if (pickupTime >= 20 || pickupTime < 6) {
cost += nightSurcharge;
}
This code right here adds nightSurcharge to the cost if pickupTime is greater than or equal to 20, OR less than 6. So of course it's added if it's less than 6.
if (pickupTime >= 20) {
cost += nightSurcharge;
}
Now it will only add to it if it's greater or equal to 20.
your code is:
if (pickupTime >= 20 || pickupTime < 6)
so if pickupTime is less then 6 it'll enter the if as well
http://jsfiddle.net/7rdzC/

Math calculation issue with Javascript

I am having a bit of trouble with a few math calculation in javascript.
The goal of this calculation is to generate a value when the user clicks on a text field.
For example:
1 Kilogram costs 32 cents to ship to America and the user wants to find out what 10KG will cost him which is $3.20. For this I have the following piece of javascript code:
function calculate(num) {
var weight = document.getElementById('weight'+num);
var price = document.getElementById('price'+num);
if(num == undefined || num == '' || num.length <= 0 || isNaN(weight.value) || isNaN(price.value)) return false;
if(num == 1) multiplyBy = 0.32;
if(num == 2) multiplyBy = 0.14;
if(num == 3) multiplyBy = 0.24;
if(num == 4) multiplyBy = 0.53;
var sum = parseInt(document.getElementById('weight'+num).value) * multiplyBy;
if(isNaN(sum)) return false;
price.value = sum;
}
The above code works perfectly fine, however when I reverse the process (someone has $3.20 and wants to find out how much KG he/she can ship with that (which is 10KG) the script returns: 9.375KG
The following code is used for this calculation:
function reverse(num) {
var weight = document.getElementById('weight'+num);
var price = document.getElementById('price'+num);
if(num == undefined || num == '' || num.length <= 0 || isNaN(weight.value) || isNaN(price.value)) return false;
if(num == 1) divideBy = 0.32;
if(num == 2) divideBy = 0.14;
if(num == 3) divideBy = 0.24;
if(num == 4) divideBy = 0.53;
var sum = parseInt(document.getElementById('price'+num).value) / divideBy;
if(isNaN(sum)) return false;
weight.value = sum;
}
I honestly don't grasp why it is failing, It would be much appreciated if someone could help me out with this.
var sum = parseInt(document.getElementById('price'+num).value) / divideBy;
You are forcing price into an integer before dividing it. So if price is 3.20, you are actually dividing 3 / 0.32, which is 9.375.
Don't force it into an integer.

Categories

Resources