1

In this jsfiddle below you will notice that the incrementing or the decrementing(?) does not work perfectly well - It goes one number off (up or down) - I am looking for a way to make it perfect.

http://jsfiddle.net/Sergelie/8d3th1cb/3/

<div data-role="page">
<div data-role="content">
    <input id="button" type="button" value="+" /> 
    <input id="button2" type="button" value="-" /> 
</div>
</div>

The idea is to go from 0 up to unlimited, and down to stop at 0 (not to -1 the way it does right now).

var count = 1;
$("#button").on('click', function () {
$(this).val(count++).button("refresh");
});
$("#button2").on('click', function () {
if (count>-1)
$("#button").val(count--).button("refresh");
});
Sergelie
  • 363
  • 1
  • 14

3 Answers3

1

You can use the prefix operator (++count/--count) instead (initializing count to 0):

var count = 0;
$("#button").on('click', function() {
  $(this).val(++count).button("refresh");
});
$("#button2").on('click', function() {
  if (count > 0)
    $("#button").val(--count).button("refresh");
});

jsFiddle example

j08691
  • 204,283
  • 31
  • 260
  • 272
0

Use ++count and --count instead so that the values are incremented/decremented before and the value of the expression is the final value:

var count = 1;
$("#button").on('click', function() {
    $(this).val(++count).button("refresh");
});
$("#button2").on('click', function() {
    if (count > 0) $("#button").val(--count).button("refresh");
});

See also: ++someVariable Vs. someVariable++ in Javascript

Community
  • 1
  • 1
Eric Hotinger
  • 8,957
  • 5
  • 36
  • 43
0
var count = 0;
$("#button").on('click', function () {
    $(this).val(++count).button("refresh");
});
$("#button2").on('click', function () {
    if (count>0)
        $("#button").val(--count).button("refresh");
});

Read about the position of increment and decrement operators here.

Adrien
  • 667
  • 6
  • 7