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.
$('.panel').append(
'<td><div class="sp-quantity">' +
'<div class="container" style=" font-size:14px; "> ' +
'<div class="sp-minus fff"> <a class="ddd" href="#">-</a>' +
'</div>' +
'<div class="sp-input">' +
'<input type="text" class="quantity-input" value="1">' +
'</div>' +
'<div class="sp-plus fff"> <a class="ddd" href="#">+</a>' +
'</div>' +
'</div></td>'
);
$(".ddd").on("click", function() {
alert('testing');
var $button = $(this),
$input = $button.closest('.sp-quantity').find("input.quantity-input");
var oldValue = $input.val(),
newVal;
if ($.trim($button.text()) == "+") {
newVal = parseFloat(oldValue) + 1;
} else {
// Don't allow decrementing below zero
if (oldValue > 0) {
newVal = parseFloat(oldValue) - 1;
} else {
newVal = 0;
}
}
$input.val(newVal);
});
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> .
$('.panel').append(
'<td><div class="sp-quantity">'+
'<div class="container" style=" font-size:14px; "> '+
'<div class="sp-minus fff"> <a class="ddd" href="#">-</a>'+
'</div>'+
'<div class="sp-input">'+
'<input type="text" class="quantity-input" value="1">'+
'</div>'+
'<div class="sp-plus fff"> <a class="ddd" href="#">+</a>'+
'</div>'+
'</div></td>'
)
$(".ddd").on("click", function () {
alert('testing');
var $button = $(this),
$input = $button.closest('.sp-quantity').find("input.quantity-input");
var oldValue = $input.val(),
newVal;
if ($.trim($button.text()) == "+") {
newVal = parseFloat(oldValue) + 1;
} else {
// Don't allow decrementing below zero
if (oldValue > 0) {
newVal = parseFloat(oldValue) - 1;
} else {
newVal = 0;
}
}
$input.val(newVal);
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
// I remove the script here
</script>
<div class="panel"></div>