i’m trying to do an price counter synchronizing with increment and decrement buttons, but the price is not changing when i click one of the buttons (+/-) this is not working, how can i solve this issue? Thanks!!!
JavaScript
x
34
34
1
$('#plus').click(function add() {
2
var $qtde = $("#quantity");
3
var a = $qtde.val();
4
5
a++;
6
$("#minus").attr("disabled", !a);
7
$qtde.val(a);
8
});
9
$("#minus").attr("disabled", !$("#quantity").val());
10
11
$('#minus').click(function minust() {
12
var $qtde = $("#quantity");
13
var b = $qtde.val();
14
if (b >= 1) {
15
b--;
16
$qtde.val(b);
17
}
18
else {
19
$("#minus").attr("disabled", true);
20
}
21
});
22
23
/* On change */
24
$(document).ready(function()
25
{
26
function updatePrice()
27
{
28
var price = parseFloat($("#quantity").val());
29
var total = (price + 1) * 1.05;
30
var total = total.toFixed(2);
31
$("#total-price").val(total);
32
}
33
$(document).on("change, keyup, focus", "#quantity", updatePrice);
34
});
JavaScript
1
6
1
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
2
<input type="button" value="-" id="minus" />
3
<input type="text" id="quantity" value="" name="quantity" />
4
<input type="button" value="+" id="plus" />
5
<br />
6
<input id="total-price" readonly="readonly" value=""/>
Advertisement
Answer
If you change your binding to update whenever there is a click on an input, you’ll get the behavior that you are expecting.
JavaScript
1
32
32
1
$('#plus').click(function add() {
2
var $qtde = $("#quantity");
3
var a = $qtde.val();
4
5
a++;
6
$("#minus").attr("disabled", !a);
7
$qtde.val(a);
8
});
9
$("#minus").attr("disabled", !$("#quantity").val());
10
11
$('#minus').click(function minust() {
12
var $qtde = $("#quantity");
13
var b = $qtde.val();
14
if (b >= 1) {
15
b--;
16
$qtde.val(b);
17
} else {
18
$("#minus").attr("disabled", true);
19
}
20
});
21
22
/* On change */
23
$(document).ready(function() {
24
function updatePrice() {
25
var price = parseFloat($("#quantity").val());
26
var total = (price + 1) * 1.05;
27
var total = total.toFixed(2);
28
$("#total-price").val(total);
29
}
30
// On the click of an input, update the price
31
$(document).on("click", "input", updatePrice);
32
});
JavaScript
1
6
1
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
2
<input type="button" value="-" id="minus" />
3
<input type="text" id="quantity" value="" name="quantity" />
4
<input type="button" value="+" id="plus" />
5
<br />
6
<input id="total-price" readonly="readonly" value="" />