Search code examples
jqueryincrementdecrement

Make this increment/decrement work with multiple inputs in jQuery


I am having a bit of trouble selecting an input. Basically, I need the button to increase or decrease the value of a single input contained in the same element.

Here's the HTML:

<div>
    <label for="name">Adult Males</label>
    <div class="dec button">-</div>
    <input type="text" name="qty" id="1" value="0" />
    <div class="inc button">+</div>
</div>
<div>
    <label for="name">Adult Females</label>
    <div class="dec button">-</div>
    <input type="text" name="adult-female" id="2" value="0"/>
    <div class="inc button">+</div>
</div>

...and the jQuery:

var incrementVar = 0;

$(function() {
    $(".inc").click(function() {
        var newValue = parseInt($(":input[name='qty']").val()) + 1;
        $(":input[name='qty']").val(newValue);
        $('.inc').addClass('a' + newValue);
        incrementVar = incrementVar + newValue;
    });
    $(".dec").click(function() {
        var newValue = parseInt($(":input[name='qty']").val()) - 1;
        $(":input[name='qty']").val(newValue);
        $('.inc').addClass('a' + newValue);
        incrementVar = incrementVar + newValue;
    });
});

This works, but only for adult-males at the moment. I want the button to target the input contained in the same div.


Solution

  • incrementVar = 0;
    $('.inc.button').click(function(){
        var $this = $(this),
            $input = $this.prev('input'),
            $parent = $input.closest('div'),
            newValue = parseInt($input.val(), 10)+1;
        $parent.find('.inc').addClass('a'+newValue);
        $input.val(newValue);
        incrementVar += newValue;
    });
    $('.dec.button').click(function(){
        var $this = $(this),
            $input = $this.next('input'),
            $parent = $input.closest('div'),
            newValue = parseInt($input.val(), 10)-1;
        $parent.find('.inc').addClass('a'+newValue);
        $input.val(newValue);
        incrementVar += newValue;
    });
    

    Demo