I am trying to increase and decrease the quantity but when i click on the + or -
, the input number doesn’t change but still remains the default value 1
.
JavaScript
x
40
40
1
$('.panel').append(
2
'<td><div class="sp-quantity">' +
3
'<div class="container" style=" font-size:14px; "> ' +
4
'<div class="sp-minus fff"> <a class="ddd" href="#">-</a>' +
5
'</div>' +
6
'<div class="sp-input">' +
7
'<input type="text" class="quantity-input" value="1">' +
8
'</div>' +
9
'<div class="sp-plus fff"> <a class="ddd" href="#">+</a>' +
10
'</div>' +
11
'</div></td>'
12
);
13
14
15
$(".ddd").on("click", function() {
16
alert('testing');
17
18
var $button = $(this),
19
$input = $button.closest('.sp-quantity').find("input.quantity-input");
20
var oldValue = $input.val(),
21
newVal;
22
23
if ($.trim($button.text()) == "+") {
24
25
newVal = parseFloat(oldValue) + 1;
26
27
} else {
28
29
// Don't allow decrementing below zero
30
if (oldValue > 0) {
31
newVal = parseFloat(oldValue) - 1;
32
} else {
33
newVal = 0;
34
}
35
}
36
37
$input.val(newVal);
38
39
});
40
Advertisement
Answer
It is only a problem related to when your <script></script>
is loaded.
Your code works when the script is loaded after your DOM. Maybe you can consider this answer to see where to put script
tag inside an html.
Also I added the class panel
inside your html: <div class="panel"></div>
.
JavaScript
1
37
37
1
$('.panel').append(
2
'<td><div class="sp-quantity">'+
3
'<div class="container" style=" font-size:14px; "> '+
4
'<div class="sp-minus fff"> <a class="ddd" href="#">-</a>'+
5
'</div>'+
6
'<div class="sp-input">'+
7
'<input type="text" class="quantity-input" value="1">'+
8
'</div>'+
9
'<div class="sp-plus fff"> <a class="ddd" href="#">+</a>'+
10
'</div>'+
11
'</div></td>'
12
13
)
14
15
$(".ddd").on("click", function () {
16
alert('testing');
17
18
var $button = $(this),
19
$input = $button.closest('.sp-quantity').find("input.quantity-input");
20
var oldValue = $input.val(),
21
newVal;
22
23
if ($.trim($button.text()) == "+") {
24
25
newVal = parseFloat(oldValue) + 1;
26
} else {
27
// Don't allow decrementing below zero
28
if (oldValue > 0) {
29
newVal = parseFloat(oldValue) - 1;
30
} else {
31
newVal = 0;
32
}
33
}
34
35
$input.val(newVal);
36
37
});
JavaScript
1
7
1
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
2
3
<script>
4
// I remove the script here
5
</script>
6
7
<div class="panel"></div>