What is the better way to counting number on different event? - javascript

I already solve it,
Here is my HTML code 👇
<strong>Product Price = $20</strong><br>
<strong>Bag Price = $10</strong><br>
<hr>
<label>Quantity of products</label>
<br>
<input type="number" id="quantity">
<br>
<input type="checkbox" id="with_bag">
<label>With a bag</label>
<br>
<p>Total Price 👇</p>
<input type="text" id="total_price" readonly>
And here is my jQuery code 👇
// Calculate total price (On Keyup)
$(document).on("keyup", "#quantity", function() {
var quantity = $('#quantity').val();
var content_price = $("#with_bag").is(':checked') ? 10 : 0;
var total_price = (20 * quantity) + content_price;
$('#total_price').val('$' + total_price.toFixed(2));
});
// Calculate total price (On Click)
$(document).on('click', '#with_bag', function(){
var quantity = $('#quantity').val();
var total_price = 20 * quantity;
if(this.checked){
total_price = (20 * quantity) + 10;
}
$('#total_price').val('$' + total_price.toFixed(2));
});
I just want to know, how to get these two different events (on keyup & on click) at the same function?

You can make a function and track your event conditionally if this is exactly what you want.
function myFunction(event){
var quantity = $('#quantity').val();
if(event.type == "keyup"){
var content_price = $("#with_bag").is(':checked') ? 10 : 0;
var total_price = (20 * quantity) + content_price;
$('#total_price').val('$' + total_price.toFixed(2));
}
else{
var total_price = 20 * quantity;
if($('#with_bag').is(":checked")){
total_price = (20 * quantity) + 10;
}
$('#total_price').val('$' + total_price.toFixed(2));
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<strong>Product Price = $20</strong><br>
<strong>Bag Price = $10</strong><br>
<hr>
<label>Quantity of products</label>
<br>
<input type="number" onkeyup="myFunction(event);" id="quantity">
<br>
<input type="checkbox" onclick="myFunction(event);" id="with_bag">
<label>With a bag</label>
<br>
<p>Total Price 👇</p>
<input type="text" id="total_price" readonly>

Related

if inside if inside if statements - is it possible?

I'm trying to display a calculation of two radio groups, in real time, before users click submit button.
<div class="container-5">
<div class="choices1">
<h1 class>Regular<br>Regular Choice</h1>
<input type="radio" id="thirteen" name="style" value="13.00">
</div>
<div class="choices2">
<h1>Popular<br>Popular Choice</h1>
<input type="radio" id="fifteen" name="style" value="15.00">
</div>
<div class="choices3">
<h1>Fancy<br>Fancy Choice<br>Literally.</h1>
<input type="radio" id="twenty" name="style" value="20.00">
</div>
</div>
<div class="container-8">
<div class="gratuity1">
<h1 class>15%<br>Good.</h1>
<input type="radio" id="15" name="tip" value=".15">
</div>
<div class="gratuity2">
<h1>20%<br>Excellent Service.</h1>
<input type="radio" id="20" name="tip" value=".20">
</div>
<div class="gratuity3">
<h1>25%<br>Beyond Excellent</h1>
<input type="radio" id="25" name="tip" value=".25">
</div>
</div>
I'm using pure javascript.
Each of these categories is suppose to represent the value of the selected radio button. Once I've defined the variables I created if statements to test if both buttons were selected and event would occur
var styleVal1= 3.0;
var styleVal2 = 5.0;
var styleVal3 = 10.0;
var tipVal1 = 0.1;
var tipVal2 = 0.15;
var tipVal3 = 0.2;
var total = 0.00;
if (document.getElementById("thirteen").selected) {
document.getElementById("thirteen").addEventListener("click", function() {
total = styleVal1;
document.getElementById("total").innerHTML = "Total:$ " + total;
if (document.getElementById("15").selected) {
total += total * tipVal1;
document.getElementById("total").innerHTML = "Total:$ " + total;
} else if (document.getElementById("20").selected) {
total += total * tipVal2;
document.getElementById("total").innerHTML = "Total:$ " + total;
} else (document.getElementById("25").selected) {
total += total * tipVal3;
document.getElementById("total").innerHTML = "Total:$ " + total;
}
});
}
I also created if statements for document.getElementById("fifteen").selected) {} and if (document.getElementById("twenty").selected {}
Am I not putting this in the right order or am I missing something? Is it even possible to do else if statements inside if statements?
As I see your JS code is wrong logically.
First of all click event is not yet binded because this condition if (document.getElementById("thirteen").selected) will always return false and event will not binded to radio element.
else cannot have a condition. else (document.getElementById("25").selected) this is wrong.
I've corrected your code but you neeed to correct the rest,
document.getElementById("thirteen").addEventListener("click", function() {
total = styleVal1;
document.getElementById("total").innerHTML = "Total:$ " + total;
if (document.getElementById("15").selected) {
total += total * tipVal1;
document.getElementById("total").innerHTML = "Total:$ " + total;
} else if (document.getElementById("20").selected) {
total += total * tipVal2;
document.getElementById("total").innerHTML = "Total:$ " + total;
} else if (document.getElementById("25").selected) { //changed this to else-if
total += total * tipVal3;
document.getElementById("total").innerHTML = "Total:$ " + total;
}
});

Working out a fixed rate and grand total in Javascript

I have a form in where a user enters information and then a calculation is performed.
For some reason, the fixed rate and my grand total isn't being outputted in the html.
Here is my script.
function updateCost()
{
var amount = $('#amount').val();
var delivery = parseInt($('#delivery').val());
var fixedrate = parseInt($('#total').val() / 100 * 12.4);
var total = parseInt(amount) + parseInt(delivery);
$("#total").html(total);
$("#amountdiv").html(amount);
$("#deliverydiv").html(delivery);
var grandtotal = parseInt(fixed) + parseInt(total);
$("#grandtotal").html(grandtotal);
$("#total").html(total);
$("#fixedrate").html(fixedrate);
}
$(document).ready(function(){
$('#amount').change(function(){ updateCost(); });
$('#delivery').change(function(){ updateCost(); });
$('#grandtotal').change(function(){ updateCost(); });
});
The HTML is this..
Payment:
<div name="amount" id="amountdiv"></div>
Freight:
<div name="delivery" id="deliverydiv"></div>
Total Payment:
<div name="total" id="total"></div>
Due Date:
<div name="date" id="date"></div>
Fixed:
<div name="fixed" id="fixedrate"></div>
Grand Total:
<div name="grandtotal" id="grandtotal"></div>
Thanks Jonah
I think you meant
var grandtotal = parseInt(fixedrate) + parseInt(total);
But also the line
var fixedrate = parseInt($('#total').val() / 100 * 12.4);
the $('#total').val() get the empty content of the div and result in 0 from the parseInt
Here is a sample of what the function could look like:
function updateCost()
{
var amount = $('#amount').val();
var delivery = parseInt($('#delivery').val());
var total = parseInt(amount) + parseInt(delivery);
$("#total").html(total);
$("#amountdiv").html(amount);
$("#deliverydiv").html(delivery);
var fixedrate = parseInt(total / 100 * 12.4);
var grandtotal = parseInt(fixedrate) + parseInt(total);
$("#grandtotal").html(grandtotal);
$("#total").html(total);
$("#fixedrate").html(fixedrate);
}
The line
var grandtotal = parseInt(fixed) + parseInt(total);
should probably be
var grandtotal = parseInt(fixedrate) + parseInt(total);

How to only add from one input field?

I want to be able to add just the article that you click on and not each. What can I use instead of .each for this to work?
These are the functions:
calculating sum total price:
var quantity, price, sum = 0;
function calculatePrice() {
//loop through product "blocks"
$('.articel').each(function() {
price = $(this).children('.price').val();
quantity = $(this).children('.quantity').val();
//Add price to sum if number
if (!isNaN(price) && !isNaN(quantity)) {
sum += price * quantity;
}
});
//Update Price
$('#totalprice').html('<h4>Total price: ' + sum + '$</h4>');
}
Add to shopping cart:
$(document).ready(function(){
$(".articel input[type='button']").click(function(){ //sätter klickfunktion på klassen artikels knapp
var price = $(this).siblings('.price').attr("value");
var quantity = $(this).siblings('.quantity').attr("value");
if(quantity % 1 != 0)
{
alert("You must add a whole number");
}
else if(quantity <= 0)
{
alert("You must att a whole number");
}
else
{
var name = $(this).siblings("input[name='prodname']").attr("value");
var ul = document.getElementById("buylist");
var totalprice = quantity * price;
var prod = name + " x " + quantity + "= " + totalprice + "$";
var el = document.createElement("li"); //skapar ett nytt element
el.innerHTML = prod; //variabeln prod läggs IN i nya elementet
ul.appendChild(el); //sätt IN el i ul
calculatePrice();
}
});
});
And this is my form:
<div id="moviescat_view" style="display:none">
<h2>Movies</h2>
<br><button onclick="backButton(moviescat_view);" class="btn">Go back</button><br>
<img border="0" id="img/hoverover.jpg" src="img/1_1.jpg" alt="The walking dead" onmouseover="mouseOverImage(this)" onmouseout="mouseOutImage(this)" onClick="addtoCart()">
</form>
<br><button onclick="showInfo(set1);" class="btn">Show info</button><br>
<h4>The walking dead</h4>
<p>Price : 30$</p>
<div id="set1" style="display:none">
<p>A serie about zombies</p>
</div>
<form class="articel">
Quantity: <input type="number" style="width:30px;" class="quantity"><br>
Add to cart: <input type="button" class="btn">
<input type="hidden" value="30" name="price" class="price">
<input type="hidden" value="The walking dead" name="prodname">
</form>
</div>
You should pass attributes to
calculatePrice();
Namely price and quantity, and then do the exact same within the function :
function calculatePrice(price, quantity) {
//Add price to sum if number
if (!isNaN(price) && !isNaN(quantity)) {
sum += price * quantity;
}
$('#totalprice').html('<h4>Total price: ' + sum + '$</h4>');
}
Like Jon said... pass in the attributes or objects that you need.
$(document).ready(function(){
$(".articel input[type='button']").click(function(){
//...
calculatePrice($(this)); //$(this) would be the clicked DOM element
});
});
function calculatePrice(element) {
price = element.children('.price').val();
quantity = element.children('.quantity').val();
//Add price to sum if number
if (!isNaN(price) && !isNaN(quantity)) {
sum += price * quantity;
}
//Update Price
$('#totalprice').html('<h4>Total price: ' + sum + '$</h4>');
}

How to show and update total price with javascript?

So I want to add a product and at the same time update the totalprice in the shopping cart.
$(".articel input[type='button']").click(function() {
var price = $(this).siblings("input[name='price']").attr("value");
var quantity = $(this).siblings("input[type='number']").attr("value");
if (quantity % 1 != 0) {
alert("You must add a whole number");
}
else if (quantity <= 0) {
alert("You can not add a negative number or nothing");
}
else {
var name = $(this).siblings("input[name='prodname']").attr("value");
var ul = document.getElementById("buylist");
var totalprice = quantity * price;
var prod = name + " x " + quantity + "= " + totalprice + "$";
var el = document.createElement("li");
el.innerHTML = prod;
ul.appendChild(el);
}
});
});
Here is where the products and totalprice adds:
<h4>Shopping Cart</h4>
<div id="buylist">
<ul>
</ul>
<div id="totalprice">
<h4>Total price:<h4>
</div>
</div>
Checkout
</div>
And here one of the forms where I add products to the cart
<form class="articel">
Quantity: <input type="number" style="width:30px;"><br>
Add to cart: <input type="button" class="btn">
<input type="hidden" value="30" name="price">
<input type="hidden" value="The walking dead" name="prodname">
</form>
Maybe I don't really understand. But when the products or their quantity change, you have to calculate the price. I suggest, that you already have an event for both of those actions. Then I'd run a function who calculates the price.
Now it depends if you already have a fix price or also have to multiply that with the quantity. Loop through the products and calculate the price.
NOTE: To select the price & quantity I used selectors which you actually don't have in your code.
function calculatePrice() {
var quantity, price, sum = 0;
//loop through product "blocks"
$('.articel').each(function() {
price = $(this).children('.price').val();
quantity = $(this).children('.quantity').val();
//Add price to sum if number
if (!isNaN(price) && !isNaN(quantity)) {
sum += price * quantity;
}
});
//Update Price
$('#totalprice').html('<h4>Total price:' + sum + '</h4');
}
If you add the price and quantity to the UL you can process easily:
<ul>
<li data-quantity="X" data-price="Z">...</li>
</ul>
Add this function to the javascript file.
function calcTotal (ul) {
var newTotal = 0;
ul.find('li').each( function(i,e) {
var li = $(e);
newTotal += li.data('quantity') * li.data('price');
});
}
Then in your code, where there is the last else:
itemPrice = quantity * price;
var prodDesc = name + " x " + quantity + "= " + itemPrice + "$";//same as it was.
var newLi = $("<li>");
newLi.text(prodDesc).data('quantity', quantity).data('price', price);
ul.append(newLi);
var totalPrice = calcTotal(ul);
$('#totalprice h4').text('Total Price: ' + totalPrice);
More or less that's it.

JavaScript - numeric data vs NaN

I'm sure I'm contravening some deep dark law of javascript, but I'm not really a JS developer and this is driving me mad. This function is called on an orderform to read the quantity and price of items, row by row, and then provide the subtotal, delivery and total.
The problem is with line 10 - it keeps "forgetting" that the variable data throughout is numeric (floating point) and so returns lots of NaN. How can I force the variables throughout this function to behave as numbers rather than strings?
EDIT
Here's the revised code based on feedback so far (thank you!). It's still not working ;)
<script type="text/javascript">
function subTotal(rows) {
var i, subTotal, lineTotal, orderShip, orderTotal;
for (i = 1; i <= rows; ++i) {
//Grab values from form
var quantity = parseFloat($('#quantity' + i).val());
var uPrice = parseFloat($('#uPrice' + i).val());
//Error checking
alert('quantity = ' + quantity +' and uPrice = ' + uPrice);
if (isNaN(quantity)) alert('quantity = NaN');
if (isNaN(uPrice)) alert('uPrice = NaN');
if ((quantity == '') || (uPrice == '')) {
} else {
lineTotal = quantity * uPrice;
alert('lineTotal = ' + lineTotal);
subTotal += lineTotal;
alert('subTotal = ' + subTotal);
}
//If we've maxed out the number of rows, then subTotal should be calculated - push back to form.
if (i == rows) {
$('#orderSubTotal').val(subTotal );
orderShip = subTotal * 0.25;
$('#orderShip').val(orderShip.toFixed(2));
orderTotal = subTotal + orderShip;
$('#orderTotal').val(orderTotal.toFixed(2));
}
}
}
</script>
<form>
<table>
<tr>
<td><input type="text" id="item1" name="item1" value="Some description" readonly="readonly" /></td>
<td><input type="text" id="quantity1" name="quantity1" value="25" onchange="javascript:subTotal('2')" /></td>
<td><input type="text" id="uPrice1" name="uPrice1" value="1.50" readonly="readonly" /></td>
</tr>
<tr>
<td><input type="text" id="item2" name="item2" value="Some description" readonly="readonly" /></td>
<td><input type="text" id="quantity2" name="quantity2" value="25" onchange="javascript:subTotal('2')" /></td>
<td><input type="text" id="uPrice2" name="uPrice2" value="2.75" readonly="readonly" /></td>
</tr>
<tr>
<td colspan="3">
SubTotal
<input type="text" id="orderSubTotal" name="orderSubTotal" readonly="readonly" style="text-align: right" value="0.00" />
<br />Shipping
<input type="text" id="orderShip" name="orderShip" readonly="readonly" style="text-align: right" value="0.00" />
<br />Total
<input type="text" id="orderTotal" name="orderTotal" readonly="readonly" style="text-align: right" value="0.00" />
</td>
</tr>
</table>
</form>
I think the real problem is in your loop: You're looping from 0 to rows inclusive. So if you pass in 10 for rows, you'll be looping 11 times, starting with 0 and continuing through (including) 10. I suspect that's your real problem. If you don't have a quantity0 element, or (assuming rows is 10) you don't have a quantity10 element, then $("#quantity" + i).val() will return undefined, which converts to NaN when you convert it (implicitly or explicitly). (And the same for uPrice0 / uPrice10.) And of course, once you have NaN, any mathematical operation using it results in NaN.
In terms of your question about how to ensure they don't change, basically, convert them to numbers early. You're currently using quantity and uPrice without converting them, which means initially they're strings. Now, JavaScript is pretty smart about converting them for you, but sometimes you want to be explicit.
Separately: Where does x come from?
You haven't shown any data to work with, but just speculatively:
function subTotal(rows) {
var i, subTotal, lineTotal, quantity, uPrice, orderShip, orderTotal;
subTotal = 0;
for (i = 0; i < rows; ++i) {
// OR
//for (i = 1; i <= rows; ++i) {
quantity = $('#quantity' + i).val();
uPrice = $('#uPrice' + i).val();
if ((quantity == '') || (uPrice == '')) {
} else {
quantity = parseFloat(quantity);
uPrice = parseFloat(uPrice);
// Might consider checking isNaN(quantity) and isNan(uPrice) here
lineTotal = quantity * uPrice;
subTotal += lineTotal;
alert('subtotal = ' + subTotal);
}
if (i == x) { // Where does `x` come from?
$('#orderSubTotal').val(subTotal );
orderShip = subTotal * 0.25;
$('#orderShip').val(orderShip.toFixed(2));
orderTotal = subTotal + orderShip;
$('#orderTotal').val(orderTotal.toFixed(2));
}
}
}
The problem is that you're performing a mathematical calculation on the fields before using parseFloat:
var lineTotal = quantity * uPrice; // <-- result is most likely NaN here
subTotal = parseFloat(subTotal ) + parseFloat(lineTotal);
Perform your parsing at the point you get the values to make life a little easier:
var quantity = parseFloat($('#quantity' + i).val());
var uPrice = parseFloat($('#uPrice' + i).val());
Then change the subTotal = line to this:
subTotal += lineTotal;
Another possible issue is if the result of $('#uPrice' + i).val() doesn't start with a parseable float — if it starts with a currency symbol, e.g. £ or $, for instance — parseFloat will always return NaN for that field. You can work around it using $('#uPrice' + i).val().slice(1).
Do some error checking:
function subTotal(rows) {
var subTotal = 0;
while (var i=0; i < rows; i++) {
// convert as soon as you get the values
var quantity = parseFloat($('#quantity' + i).val());
var uPrice = parseFloat($('#uPrice' + i).val());
if (isNaN(quantity) || isNaN(uPrice)) { // error checking
alert("Invalid values on row " + i);
continue;
}
var lineTotal = quantity * uPrice;
subTotal += lineTotal;
alert('subtotal = ' + subTotal);
if (i == x) {
$('#orderSubTotal').val(subTotal );
var orderShip = subTotal * 0.25;
$('#orderShip').val(orderShip.toFixed(2));
var orderTotal = subTotal + orderShip;
$('#orderTotal').val(orderTotal.toFixed(2));
}
}
}
You're probably running into an index problem at some point, getting a NaN from one of the (non-existing fields), adding it to subTotal which makes it a NaN instantly.
You better convert the value before doing any mathematical operation. So the code should be:
var numQuanitity = parseFloat(quantity);
var numPrice = parseFloat(uPrice);
if (isNaN(numQuanitity) || isNaN(numPrice)) {
//you can alert or ignore
}
else {
var lineTotal = numQuanitity * numPrice;
subTotal += lineTotal;
alert('subtotal = ' + subTotal);
}
...

Categories