custom amount subtraction from more than one cell in html table - javascript

$(".submitNum").click(function() {
var $tr = $(this).closest('tr');
var $remaining = $tr.find(".remaining");
var $qty = $tr.find(".stockQuantity");
var $numToSubmit = $tr.find(".customInput");
//Get current values
var batchSize = $remaining.attr("data-maxNumber");
var currentRemaining = $remaining.text();
var currentQty = $qty.text();
var currentInputValue = $numToSubmit.val();
var difference = Number(currentRemaining) - Number(currentInputValue);
var divisible = Number(currentInputValue) / Number(batchSize);
var usesFromQuantity = Number(currentQty) * Number(batchSize);
var totalUses = Number(usesFromQuantity) + Number(currentRemaining);
var decimalPart = divisible - Math.round(divisible);
var finalRemaining = Number(decimalPart) * Number(batchSize);
//Subtract values
if (currentInputValue < 0) {
alert('Please insert a valid quantity to withdraw');
} else if (currentInputValue > totalUses) {
alert("Cannot withdraw this amount");
} else if (currentInputValue > Number(batchSize) + Number(currentRemaining) &&
Number(currentInputValue) < Number(totalUses)) {
currentQty = Number(currentQty) - Math.round(divisible);
currentRemaining = Math.round(finalRemaining);
} else if (difference == 0) {
currentRemaining = batchSize;
currentQty = currentQty - 1;
} else if (difference < 0) {
currentRemaining = Number(difference) + Number(batchSize);
currentQty = Number(currentQty) - 1;
} else if (difference > 0) {
currentRemaining = difference;
} else if (currentInputValue == totalUses) {
currentRemaining = 0;
currentQty = 0;
}
//Update text
$remaining.text(currentRemaining);
$qty.text(currentQty);
$tr.find(".collapseX").hide();
$tr.find(".inputBtn").show();
$tr.find('.customInput').val('');
});
ul li {
display: inline;
}
body {
text-align: center;
}
input {
max-width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table">
<thead>
<tr>
<th scope="col">Item</th>
<th scope="col">Stock Quantity</th>
<th scope="col">Remaining Uses</th>
<th scope="col">Withdraw Item</th>
</tr>
</thead>
<tbody>
<tr>
<td>#Item1</td>
<td class="stockQuantity">3</td>
<td data-maxNumber="30" class="remaining">15</td>
<td>
<ul>
<li class="list-inline-item">
<input placeholder="Set uses qty" class="customInput" type="number" min="1">
</li>
<li class="list-inline-item"><button href="#" class=" submitNum">Sumit</button></li>
</ul>
</td>
</tr>
</tbody>
</table>
Okay so:
1 unit of stock quantity has 30 x remaining uses
What I am confused in is creating an algorithm that calculates how much is left in the stock quantity and the remaining uses if the value of the input field is an amount that exceeds the current remaining uses + 30 which is the amount per 1 unit of stock quantityso I can know how many units should I withdraw from stock quantity and how many units should be remaining in remaining uses.
The jquery function I have here is a bit big and cluttered, but its functional when I want to withdraw an amount that is less than or equal remaining uses + 30.
of course there can be smarter ways to do this feel free to change the whole thing
to understand what I mean better try withdrawing (45 units) or less it'll work and then try to withdraw (70 units) here you'll notice the bug.

You can use the modulus operator (%) to quickly figure out how many come out of remaining.
Say you have:
var qty = 3;
var remaining = 20;
var batchSize = 30;
var withdrawAttempt = 45;
Then:
var totalLeft = remaining + batchSize * qty;
if (withdrawAttempt > totalLeft) {
// invalid
} else {
// calculate how many to take from remaining
var wr = withdrawAttempt % batchSize;
// update qty and remaining
qty -= (withdrawAttempt - wr) / batchSize;
remaining -= wr;
if (remaining < 0) {
remaining += batchSize;
qty -= 1;
}
}

Related

Removing the shipping price, if the amount has reached a certain value

So I have a working shopping cart page, but I do not know how to remove the shipping value, once a user has reached a total, for example, of 50 or higher. In the previous version this was already implemented, so I tried to compare and figure out how to implement this in the new page, but am not skilled enough in JavaScript. This is the JavaScript I am using right now.
$(document).ready(function() {
var taxRate = 0.05;
var shippingRate = 5.00;
var fadeTime = 300;
$('.product-quantity input').change( function() {
updateQuantity(this);
});
$('.product-removal button').click( function() {
removeItem(this);
});
function recalculateCart()
{
var subtotal = 0;
$('.product').each(function () {
subtotal += parseFloat($(this).children('.product-line-price').text());
});
var tax = subtotal * taxRate;
var shipping = (subtotal > 0 ? shippingRate : 0);
var total = subtotal + tax + shipping;
$('.totals-value').fadeOut(fadeTime, function() {
$('#cart-subtotal').html(subtotal.toFixed(2));
$('#cart-tax').html(tax.toFixed(2));
$('#cart-shipping').html(shipping.toFixed(2));
$('#cart-total').html(total.toFixed(2));
if(total == 0){
$('.checkout').fadeOut(fadeTime);
}else{
$('.checkout').fadeIn(fadeTime);
}
$('.totals-value').fadeIn(fadeTime);
});
}
function updateQuantity(quantityInput)
{
var productRow = $(quantityInput).parent().parent();
var price = parseFloat(productRow.children('.product-price').text());
var quantity = $(quantityInput).val();
var linePrice = price * quantity;
productRow.children('.product-line-price').each(function () {
$(this).fadeOut(fadeTime, function() {
$(this).text(linePrice.toFixed(2));
recalculateCart();
$(this).fadeIn(fadeTime);
});
});
}
function removeItem(removeButton)
{
var productRow = $(removeButton).parent().parent();
productRow.slideUp(fadeTime, function() {
productRow.remove();
recalculateCart();
});
}
});
Set shipping to zero when subtotal + tax >= 50 (assuming that's the business rule).
var shipping = subtotal > 0 && (subtotal + tax < 50) ? shippingRate : 0;
And then, for display purposes, set the shipping value element to empty when shipping === 0. A ternary operator is one way to do it.
$('#cart-shipping').html(shipping === 0 ? '' : shipping.toFixed(2));

How to calculate total?

I faced a problem for my code and I could not solve it. I have 2 functions, the first one calculates the total and second one discounts the total (if the user write the discount code, it will show the discounted total). But I don't know how to get and call the right value from total to keep it in the second function to calculate the discount because it always shows 0 in the amount. The TOTAL is for the first function and JavaScript code is for the second function.
total = parseInt(TicketsPrice[i].value) * parseInt(NOfTictet);
document.getElementById("total").innerHTML = total;
function discount(coupon) {
var yCoupon = "winner1";
var price = Number(document.getElementById('total').innerHTML);
var amount;
var input = document.getElementById('discount').value;
if (input == coupon) {
amount = price || 0 * 0.25;
document.getElementById("Offerprice").innerHTML = amount;
} else {
alert("Invalid");
}
}
<input type="text" name="coupon" id="discount">
<button onclick="discount()">discount</button>
<p id="total"></p>
<p><span id="Offerprice"></span></p>
Something like this?
function discount() {
var coupon = "winner1";
var price = Number(document.getElementById('total').value);
var input = document.getElementById('discount').value;
if (input == coupon) {
var amount = price * (1 - .25) // 25% off coupon
document.getElementById("Offerprice").innerHTML = amount;
} else {
document.getElementById("Offerprice").innerHTML = 'Invalid coupon'
}
}
<div>Total: <input id="total"></div>
<div>Coupon: <input id="discount"></div>
<button onclick="discount()"> discount</button>
<p><span id ="Offerprice"></span></p>
You have several issues in your code. Here is a working version. I hardcoded the total only for testing because I don't know the HTML for your tickets:
var total = 500; //This is only for testing.
document.getElementById("total").innerHTML = total;
function discount() {
var coupon = "winner1";
var price = Number(document.getElementById('total').innerHTML);
var input = document.getElementById('discount').value;
if (input == coupon) {
var amount = price * 0.75; //discount of 25%
document.getElementById("Offerprice").innerHTML = amount;
} else {
alert("Invalid");
}
}
<input type="text" name="coupon" id="discount">
<button onclick="discount()">discount</button>
<p id="total"></p>
<p><span id="Offerprice"></span></p>

Sharing random variables between functions

I'm trying to code a game and part of it has a combat system. I want the player to click a button as many times as they want to find an opponent, then to click the attack button when they find one they like and a timed event happens to slowly reveal the result.
The problems I'm coming against are:
- If the VAR are outside the functions, then you can only infiltrate once, but if it's inside the first function then the other ones can't use those values for the battle.
- The max_acres for victory comes across as a string so instead of 10+3=13, it becomes 103. How can I fix that?
Thank you very much for looking and I appreciate the help!
Javascript:
var titles = ["Peasant", "Knight"];
var first = ["Ada", "Adro", "Ama"];
var last = ["nija", "har", "nake"];
var random_name1 = titles[Math.floor(Math.random() * titles.length)] + ' ' + first[Math.floor(Math.random() * first.length)] + last[Math.floor(Math.random() * last.length)];
var random_acres1 = (max_acres * (Math.floor(Math.random() * (140 - 75)) + 75) / 100).toFixed(0);
var random_troops1 = (random_acres1 * (Math.floor(Math.random() * (1500 - 600)) + 600) / 100).toFixed(0);
var random_off1 = (random_troops1 * (Math.floor(Math.random() * (1200 - 400)) + 400) / 100).toFixed(0);
var combat_victory_acres1 = (random_acres1 * (((Math.random() * (35 - 11)) + 11) / 100)).toFixed(0);
var combat_defeat_acres1 = (random_acres1 * (Math.floor(Math.random() * (20 - 11)) + 11) / 100).toFixed(0);
var text_victory = 'You have been awarded with ';
var text_defeat = 'You have lost control of ';
var text_acres = ' acres.';
function infiltrate(){
var x = document.getElementById("Combat_table");
if (x.style.display === "none") {
x.style.display = "block";
}
document.getElementById('combat_army_strength').innerHTML = army_strength;
document.getElementById('combat_max_acres').innerHTML = max_acres;
document.getElementById('random_name1').innerHTML = random_name1;
document.getElementById('random_acres1').innerHTML = random_acres1;
document.getElementById('random_troops1').innerHTML = random_troops1;
document.getElementById('random_off1').innerHTML = random_off1;
};
function attack_random1(){
document.getElementById("attack_button1").style.display="none";
document.getElementById("infiltration").style.display="none";
var y = document.getElementById("Combat_Results");
if (y.style.display === "none") {
y.style.display = "block";
}
setTimeout(Combat_Text4, 5000)
var final_outcome1 = army_strength - random_off1;
if (final_outcome1 >= 0) {
setTimeout(Combat_Text_Victory1, 6000);
} else {
setTimeout(Combat_Text_Defeat1, 6000);
}
};
function Combat_Text4() {
document.getElementById("Combat_Results4").innerHTML = "The battle is over, a scout is dispatched to you with the results.";
}
function Combat_Text_Victory1() {
max_acres = max_acres + combat_victory_acres1;
var text_victory_1 = text_victory + combat_victory_acres1 + text_acres;
document.getElementById("Combat_Results5").innerHTML = "You achieved <b>Victory!</b>";
document.getElementById("Combat_Results6").innerHTML = text_victory_1;
document.getElementById('max_acres').innerHTML = max_acres;
document.getElementById('combat_max_acres').innerHTML = max_acres;
}
function Combat_Text_Defeat1() {
max_acres = max_acres - combat_defeat_acres1;
var text_defeat_1 = text_defeat + combat_defeat_acres1 + text_acres;
document.getElementById("Combat_Results5").innerHTML = "You have been <b>Defeated!</b>";
document.getElementById("Combat_Results6").innerHTML = text_defeat_1;
document.getElementById('max_acres').innerHTML = max_acres;
document.getElementById('combat_max_acres').innerHTML = max_acres;
}
HTML:
<div id="Combat" class="tabcontent">
Total Land: <span id="combat_max_acres">10</span><br>
Total Offense: <span id="combat_army_strength">0</span><p>
<button id="infiltration" onclick="infiltrate()">Infiltrate Kingdoms</button>
<div id="Combat_table" style="display: none">
<center><table>
<tr valign="center">
<th>Kingdom Name</th>
<th>Acres</th>
<th>Troop <br>Numbers</th>
<th>Total <br>Offense</th>
<th></th>
</tr>
<tr id="combat_row1">
<td><span id="random_name1"></span></td>
<td><span id="random_acres1"></span></td>
<td><span id="random_troops1"></span></td>
<td><span id="random_off1"></span></td>
<td><button onclick="attack_random1()" id="attack_button1">Attack!</button></td>
</tr>
</table>
</div>
<br>
<div id="Combat_Results" style="display: none">
<center><table><tr>
<td><center><span id="Combat_Results4"></span></td>
</tr><tr>
<td><center><span id="Combat_Results5"></span></td>
</tr><tr>
<td><center><span id="Combat_Results6"></span></td>
</tr>
</table>
</div>
The max_acres for victory comes across as a string so instead of 10+3=13, it becomes 103. How can I fix that?
Use Math.round instead of Number#toFixed, because for addition numerical values, you need both operands as number, not a string.
Use toFixed only for displaying a number.
For the other parts, I suggest to use an object with arrays for same items, like
{
name: [],
acres: [],
troops: [],
off: [],
victory_acres: [],
combat_defeat_acres: [],
// etc.
}

Donation days calculator issue

Hey i'd like to know how can i make such calculator
by entering the $ amount you get how many days of donation status
as shown here
https://www.sixth-sen.se/index.php?/donate/
i tried several ways and codes but none of them worked
Don't use <center>, it's old and deprecated. Instead, use CSS:
$(document).ready(function() {
var promotion = 3;
$("#donations").keyup(function() {
var amount = $("#donations").val();
if (amount == "") {
$("#donation_amout").html("<h3>You have not entered any amount.</h3>");
document.getElementById('amount').value = amount;
} else if (amount < 0.50) {
$("#donation_amout").html("<h3>Not acceptable, must be higher than $0.50!</h3>");
document.getElementById('amount').value = amount;
} else if (amount < 1) {
var count = amount * promotion;
$("#donation_amout").html("<h3>Contributor Status for <b>0</b> days</h3>");
document.getElementById('amount').value = amount;
} else if (amount >= 1 && amount < 100000000) {
var count = Math.floor(amount) * promotion;
$("#donation_amout").html("<h3>Contributor Status for <b>" + count + "</b> days</h3>");
document.getElementById('amount').value = amount;
} else if (amount > 100000000) {
$("#donation_amout").html("<h3>The amount is out of range!</h3>");
document.getElementById('amount').value = amount;
}
});
});
.amount {
margin: auto;
width: 20%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="amount">
<h2>Donation Amount</h2>
<b>$</b>
<input type="text" placeholder="Input the donation amount and discover what you'd get" id="donations" name="donation">
<div id="donation_amout"></div>
</div>

Calculate the price of the items, depending on its quantity

I'm trying to make block with the prices. The unit price varies depending on its quantity of units. For example:
Quantity — Price for each
1____________________$110
10___________________$105
20___________________$100
...
Number of items:__
Total:
Price for each:
There is a need to write a the text field into which the user enters the number of items, and everything is recalculating and summing on the fly.
Here is my realization of this task:
var price1 = 110,
price2 = 105,
price3 = 100,
qty1 = 1,
qty2 = 10,
qty3 = 20;
function conversion(val) {
var div = document.getElementById("div"),
price = document.getElementById("price");
if (isNaN(val)) {
div.innerHTML = "";
price.innerHTML = "";
} else {
switch (true) {
case (val <= 0):
{
div.innerHTML = "";
price.innerHTML = "";
break;
}
case (val >= qty1 && val < qty2):
{
div.innerHTML = val * price1;
price.innerHTML = price1;
break;
}
case (val >= qty2 && val < qty3):
{
div.innerHTML = val * price2;
price.innerHTML = price2;
break;
}
case (val >= qty3):
{
div.innerHTML = val * price3;
price.innerHTML = price3;
break;
}
}
}
}
<div>
Quantity — Price for each
</div>
<div>
<div>1 — $110</div>
<div>10 — $105</div>
<div>20 — $100</div>
</div>
<div>
Number of items:
<div>
<input id="txt" onblur="conversion(this.value)" onchange="conversion(this.value)" onkeypress="conversion(this.value)" onkeyup="conversion(this.value)" type="number">
</div>
</div>
<div>
Total:
<div id="div"></div>
</div>
<div>
Price for each:
<div id="price"></div>
</div>
How it can be properly implemented, taking into account the fact that the lines with the quantity and unit price can be from one to infinity (values are taken from the database)?
I think it is possible to record the price and quantity in data-atributes and parse it with JS. Like this:
...
<div data-quantity="10" data-price="105">
<span class="quantity">10</span>
<span class="price">105</span>
</div>
...
Thanks!
Using the data attribute is indeed a solution:
console.log(document.getElementById("test").dataset)
<div data-quantity="10" data-price="105" id="test">
<span class="quantity">10</span>
<span class="price">105</span>
</div>
It's not fully compatible with previous IE version though, so be careful with it.
I would however suggest that you look for a way of moving your calculations away from the DOM to speed up your calculations.
For instance, parsing the data to a JavaScript object and doing the calculations there would save you some DOM trips and thus speed:
console.clear();
//markup for product
function Product(name) {
return {
//Name of product
name : name,
//List of price ranges (populated later)
prices : [
],
//method for adding a price
newPrice : function newPrice(quantity, cost) {
//Push new price unto list
this.prices.push({
quantity : quantity,
cost : cost
});
//Sort list
this.prices = this.prices.sort(function (a, b) {
return a.quantity - b.quantity
});
},
//Get the price for a variable quantity of this product
get : function (quantity) {
//Loop through prices to find the most matching
var price = 0;
for (var i = 0; i < this.prices.length; i++) {
if (this.prices[i].quantity <= quantity) {
price = this.prices[i].cost;
} else {
break;
}
}
console.log('price per unit:', price, 'price for all', quantity, 'units:', price * quantity)
}
};
} //Make an instance
var myHotProduct = new Product('Fancy pants');
//Add some prices
myHotProduct.newPrice(0, 110);
myHotProduct.newPrice(10, 105);
myHotProduct.newPrice(20, 100);
//get some quantities
myHotProduct.get(0);
myHotProduct.get(1);
myHotProduct.get(9);
myHotProduct.get(10);
myHotProduct.get(19);
myHotProduct.get(20);
//Log everything we know about our product
console.log(myHotProduct);
Now you can get your prices as arrays and modify them outside of the limitations of data-.

Categories

Resources