Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quantity increase using plus and minus with jQuery not working

Tags:

html

jquery

css

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);

});
like image 570
Vikas Ghodke Avatar asked Dec 05 '22 08:12

Vikas Ghodke


2 Answers

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>
like image 60
Rory McCrossan Avatar answered Jan 11 '23 21:01

Rory McCrossan


Your selector for input should be

$button.closest('.sp-quantity').find("input.quntity-input")

Demo: Fiddle

like image 24
Arun P Johny Avatar answered Jan 11 '23 19:01

Arun P Johny