Hi i am creating an input number increment using jQuery but no success yet can you please check my code and give me a proper guidance
SEE THE DEMO HERE
HTML
<div class="sp-quantity">
<div class="sp-minus fff"> <a class="ddd" href="#">-</a></div>
<div class="sp-input">
<input type="text" class="quntity-input" value="1">
</div>
<div class="sp-plus fff"> <a class="ddd" href="#">+</a></div>
</div>
JS
$(".ddd").on("click", function () {
var $button = $(this);
var oldValue = $button.parent().find("input .quntity-input").val();
if ($button.text() == "+") {
var newVal = parseFloat(oldValue) + 1;
} else {
// Don't allow decrementing below zero
if (oldValue > 0) {
var newVal = parseFloat(oldValue) - 1;
} else {
newVal = 0;
}
}
$button.parent().find("input .quntity-input").val(newVal);
});
The selector for finding your input was incorrect. .quntity-input
is a child of the .sp-quantity
which is two levels above the button in the DOM, so you need to use closest()
with a selector, not parent
. Try this:
$(".ddd").on("click", function () {
var $button = $(this);
var oldValue = $button.closest('.sp-quantity').find("input.quntity-input").val();
if ($button.text() == "+") {
var newVal = parseFloat(oldValue) + 1;
} else {
// Don't allow decrementing below zero
if (oldValue > 0) {
var newVal = parseFloat(oldValue) - 1;
} else {
newVal = 0;
}
}
$button.closest('.sp-quantity').find("input.quntity-input").val(newVal);
});
Example fiddle
You can also simplify your code:
$(".ddd").on("click", function() {
var $button = $(this);
var $input = $button.closest('.sp-quantity').find("input.quntity-input");
$input.val((i, v) => Math.max(0, +v + 1 * $button.data('multi')));
});
.sp-quantity div { display: inline; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="sp-quantity">
<div class="sp-minus fff"><a class="ddd" href="#" data-multi="-1">-</a></div>
<div class="sp-input">
<input type="text" class="quntity-input" value="1" />
</div>
<div class="sp-plus fff"><a class="ddd" href="#" data-multi="1">+</a></div>
</div>
Your selector for input should be
$button.closest('.sp-quantity').find("input.quntity-input")
Demo: Fiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With