Donation days calculator issue - javascript

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>

Related

Input not being read by code in JavaScript

I'm having trouble with my JS form. So I'm creating a change calculator which takes in two input values - the price and cash. When I explicity put in the actual values inside JS code (like the ones I commented out after confirmValues()), it works just fine. But when I put it in the actual input box, it doesn't give work anymore. Is there something weird with my HTML or JS? Thanks!
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=">
<title> Change calculator</title>
</head>
<body>
<form>
How much does the item cost? <input type="number" id="price" name ="price"/>
<br/> <br/>
How much cash do you have? <input type="number" id="cash" name="cash"/><br/> <br/>
<input type="button" value="Enter" onclick="confirmItems();"/>
</form>
<p id="confirmation"></p>
<p id ="change"></p>
</body>
var itemCost = document.getElementById("price");
var cash = document.getElementById("cash");
var confirmation = document.getElementById("confirmation");
function confirmItems() {
confirmation.innerHTML = "Your total purchase costs $" + itemCost.value + " and you have $" + cash.value + " to pay for it.";
createConfirmationBtn();
}
function createConfirmationBtn() {
let confirmationBtn = document.createElement("BUTTON");
const confirmationBtnText = document.createTextNode("Confirm");
confirmationBtn.appendChild(confirmationBtnText);
confirmation.appendChild(confirmationBtn);
confirmationBtn.onclick = function() {
confirmValues();
}
}
let changeEl = document.getElementById("change");
function confirmValues() {
if (parseFloat(cash.value) < parseFloat(itemCost.value)) {
changeEl.innerHTML = "Not enough cash";
} else if (parseFloat(cash.value) == parseFloat(itemCost.value)) {
changeEl.innerHTML = "Your change is $0.";
} else {
calculateChange();
}
}
// cash.value = 500;
// itemCost.value = 33.44;
let remainder = parseFloat(cash.value) - parseFloat(itemCost.value);
let finalOutput = new Array();
function calculateChange() {
while (remainder > 0) {
if (remainder >= 100) {
findChange(100.00);
} else if (remainder >= 50.00) {
findChange(50.00);
} else if (remainder >= 20.00) {
findChange(20.00);
} else if (remainder >= 10.00) {
findChange(10.00);
} else if(remainder >= 5.00) {
findChange(5.00);
} else if (remainder >= 1.00) {
findChange(1.00);
} else if (remainder >= 0.25) {
findChange(0.25);
} else if (remainder >= 0.10) {
findChange(0.10);
} else if (remainder >= 0.05) {
findChange(0.05);
} else {
findChange(0.01);
}
}
changeEl.innerHTML = finalOutput;
}
function findChange(value) {
//Step 1. Get number of dollar for each type of dollar
let dValue = parseInt(remainder / value);
// Step 2. Storing numDValue in an array
finalOutput.push("[$" + value + " x" + dValue+"]");
remainder = parseFloat(remainder - (value * dValue));
remainder = parseFloat(remainder.toFixed(2));
}
You need to have the vars inside the functions that need them or they will not pick up what the user enters
You can show and hide the confirm button
DRY, Don't Repeat Yourself
function confirmValues() {
let itemCost = document.getElementById("price").value;
let cash = document.getElementById("cash").value;
const confirmation = document.getElementById("confirmation");
const changeEl = document.getElementById("change");
const confirm = document.getElementById("confirm");
cash = isNaN(cash) || cash === "" ? 0 : +cash; // test valid input
itemCost = isNaN(itemCost) || itemCost === "" ? 0 : +itemCost;
if (cash < itemCost) {
changeEl.innerHTML = "Not enough cash";
} else {
confirmation.innerHTML = "Your total purchase costs $" + itemCost.toFixed(2) + " and you have $" + cash.toFixed(2) + " to pay for it.";
changeEl.innerHTML = "Your change is $" + (cash - itemCost).toFixed(2);
confirm.classList.remove("hide");
}
}
.hide {
display: none;
}
<title> Change calculator</title>
<form>
How much does the item cost? <input type="number" id="price" name="price" />
<br/> <br/> How much cash do you have? <input type="number" id="cash" name="cash" /><br/> <br/>
<input type="button" value="Enter" onclick="confirmValues();" />
<input type="button" id="confirm" class="hide" value="Confirm" onclick="alert('Confirmed!')" />
</form>
<p id="confirmation"></p>
<p id="change"></p>

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>

custom amount subtraction from more than one cell in html table

$(".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;
}
}

How would I activate my script on button click only?

So my HTML is:
<!DOCTYPE>
<head>
<script src="js/problem1.js"></script>
</head>
<body>
<input id="clickMe" type="button" value="Problem #1" onclick="problem1();" />
<script src="js/problem1.js"></script>
</body>
The script I am trying to run is:
var counter = 0
var total = 0
var start = prompt("Enter a number here to find the sum of all numbers that are:\n-Between 0 and your number\n-Divisible by 3 or 5")
function problem1(start) {
for (counter = 0; counter < start; counter++) {
if (counter < start) {
if (counter % 3 == 0) {
total += counter;
}
else if (counter % 5 == 0) {
total += counter;
}
}
else if (counter == start) {
if (counter % 3 == 0) {
total += counter;
alert(total);
}
else if (counter % 5 == 0) {
total += counter;
alert(total);
}
else {
alert(total);
}
}
}
}
The problem I am running into is that right now the script runs on page load and instantly gives me a prompt for creating the start variable. After entering an integer and clicking Ok the prompt window disappears and nothing happens. I do realize that the script is running on its own because it is called in the <head>. Problem is I don't know how else to call it, like on button click. I don't want to use JQuery. I have seen lots of answers like this one but I am looking for something that doesn't require JQuery. How would I accomplish this?
UPDATE
Thank you for the help. Now I have stumbled upon a second problem. I can't get the script to run or display the alert (not sure which)
put your prompt inside the problem function
function problem1() {
var counter = 0
var total = 0
var start = prompt("Enter a number here to find the sum of all numbers that are:\n-Between 0 and your number\n-Divisible by 3 or 5")
for (counter = 0; counter < start; counter++) {
if (counter < start) {
if (counter % 3 == 0) {
total += counter;
alert(total);
}
else if (counter % 5 == 0) {
total += counter;
alert(total);
}
}
else if (counter == start) {
if (counter % 3 == 0) {
total += counter;
alert(total);
}
else if (counter % 5 == 0) {
total += counter;
alert(total);
}
else {
alert(total);
}
}
}
}
<!DOCTYPE>
<head>
<script src="js/problem1.js"></script>
</head>
<body>
<input id="clickMe" type="button" value="Problem #1" onclick="problem1();" />
<script src="js/problem1.js"></script>
</body>

Categories

Resources