1

I got this simple function that counts clicks (plus or minus). It works correctly. The fact is that negative values appear with the minus symbol in front of them (eg. -3), but it's not the same for positive ones.

Is there a way to have positive results show the plus symbol at the beginning (eg. +3)?

$('#increase').click(function() {
  $('#output').html(function(i, val) {
    return val * 1 + 1
  });
});

$('#decrease').click(function() {
  $('#output').html(function(i, val) {
    return val * 1 - 1
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="increase" type="button">+</button>
<button id="decrease" type="button">-</button>
<div id="output">10</div>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339

2 Answers2

4

To achieve this you can simply check if the value is > 0, and if so prepend a + to it.

Also note that you can DRY up the code by using a data attribute on the button to specify the value to increment by. This means you can then use a single event handler on both buttons, like this:

$('button').click(function() {
  var $btn = $(this);
  $('#output').html(function(i, val) {
    val = val * 1 + $btn.data('inc');
    return (val <= 0 ? '' : '+') + val;
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="increase" type="button" data-inc="1">+</button>
<button id="decrease" type="button" data-inc="-1">-</button>
<div id="output">+10</div>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
0

$('#increase').click(function() {
    $('#output').html(function(i, val) { 
        if (val < 11) {
            var ret = val * 1 + 1;
        }
        return ret > 0 ? "+" + ret : ret;
    });
});
$('#decrease').click(function() {
    $('#output').html(function(i, val) { 
        if(val > -11) {
           var ret = val * 1 - 1;
        }
        return ret > 0 ? "+" + ret : ret;
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="increase" type="button">+</button>
<button id="decrease" type="button">-</button>
<div id="output">+10</div>
kevinSpaceyIsKeyserSöze
  • 3,693
  • 2
  • 16
  • 25
  • 1
    `var ret = val * 1 + 1;` should be `var ret = val * 1 - 1;` in the decrease function. Also, recommend starting with +10 rather than 10 to maintain that "+" for positives. – Cheryl Velez Sep 01 '17 at 12:08
  • Hi, thank you, would it be possible to set a max amount to the counter? I need it to stop counting over +11 and under -11 (need it to work only between -11 and +11 included) – Alberto Moneti Sep 01 '17 at 16:20