I am trying to create a input for Quantity (Plus/Minus Buttons) but I can’t get it to sum up the price when a different quantity is chosen.
For example, if the item is £2.00 and 2x quantity is chosen then it should display £4.00 instead
Here is what I have so far..
function increaseCount(a, b) {
var input = b.previousElementSibling;
var value = parseInt(input.value, 10);
value = isNaN(value) ? 0 : value;
value++;
input.value = value;
}
function decreaseCount(a, b) {
var input = b.nextElementSibling;
var value = parseInt(input.value, 10);
if (value > 1) {
value = isNaN(value) ? 0 : value;
value--;
input.value = value;
}
}
$('#quantity').change(function (event) {
$('#price').html($(this).val() * parseInt($('#price').text(), 10));
});
.counter {
width: 150px;
margin: auto;
display: flex;
align-items: center;
justify-content: center;
}
.counter input {
background:none;
margin:0px 12px;
width:80px;
border:1px solid #0052cc;
line-height:34px;
font-size:20px;
text-align:center;
color:var(--text-color);
appearance:none;
outline:0;
}
.counter span {
background:#0052cc;
display: block;
font-size: 25px;
padding:0 10px;
cursor: pointer;
color:#111;
user-select: none;
}
<div class="counter">
<span class="down" onClick='decreaseCount(event, this)'>-</span>
<input type="text" id="quantity" value="1" name="quantity">
<span class="up" onClick='increaseCount(event, this)'>+</span>
</div>
Price: £<span id="price" value="2.00"></span>2.00
2
Answers
The "updateTotalPrice" function is called from within the "increaseCount", "decreaseCount", and "change" event listeners to ensure that the total price is always up-to-date. The "price" element is used to display the calculated total, which is formatted to two decimal places using the "toFixed" method.
You can do it by adding a
function
that will be called when increase or decrease the quantity to update prices :