1

I want to have multiple plus/minus counters on my page.

I have one working counter but want to make it generic so that multiple counters can have a different initial value and increase and decrease as clicked.

$('.counter-btn').click(function(e) {
    e.preventDefault();
    var $btn = $(this);
    $('.output').html(function(i, val) {
        val = val * 1 + $btn.data('inc');
        return (val <= 0 ? '' : '+') + val;
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="counter-btn" id="increase1" type="button" data-inc="1">+</button>
<button class="counter-btn" id="decrease1" type="button" data-inc="-1">-</button>
<div class="output">+30</div>

<hr />


<button class="counter-btn" id="increase1" type="button" data-inc="1">+</button>
<button class="counter-btn" id="decrease1" type="button" data-inc="-1">-</button>
<div class="output">+30</div>

Fiddle Link: http://jsfiddle.net/u2Lh7dbp/

Thanks

John
  • 1,777
  • 9
  • 42
  • 66

2 Answers2

2

Each output element should be unique so it can be called by itself.

$('.counter-btn').click(function(e) {
        e.preventDefault();
        var $btn = $(this);
        $('#output-' + $btn.data('index')).html(function(i, val) {
            val = val * 1 + $btn.data('inc');
            return (val <= 0 ? '' : '+') + val;
        });
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="counter-btn" id="increase1" type="button" data-index="1" data-inc="1">+</button>
<button class="counter-btn" id="decrease1" type="button" data-index="1" data-inc="-1">-</button>
<div class="output" id="output-1">+30</div>

<hr />

<button class="counter-btn" id="increase2" type="button" data-index="2" data-inc="1">+</button>
<button class="counter-btn" id="decrease2" type="button" data-index="2" data-inc="-1">-</button>
<div class="output" id="output-2">+30</div>

I've added a new data attribute: index. You can use that index to specify the exact output element you're looking for by its id.

halfpastfour.am
  • 5,764
  • 3
  • 44
  • 61
2

Keeping it simple, you can have two functions and directly associate the onClick callback to these functions, making it more clear on the html side.

function add(id) {
    var newCount = parseInt($(id).text()) + 1;
    $(id).text(newCount);
}

function substract(id) {
    var newCount = parseInt($(id).text()) - 1;
    $(id).text(newCount);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" onclick="add('#output1')">+</button>
<button type="button" onclick="substract('#output1')">-</button>
<div id="output1">30</div>

<hr />

<button type="button" onclick="add('#output2')">+</button>
<button type="button" onclick="substract('#output2')">-</button>
<div id="output2">30</div>
Kevin Pastor
  • 761
  • 3
  • 18