4

Astonished to find out that a line like this :

$('#TextBox').val(parseInt($('#TextBox').val())++ );

Will not work !

I've done some tests, it plays out to the conclusion that the inline ++ doesn't work (in Javascript as a whole ? Or simply in my example ?).

Here's a test with three pieces of code, it seems that ++ is ok with a variable but not inline.

So, no inline ++ for us in Javascript?

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Akheloes
  • 1,352
  • 3
  • 11
  • 28
  • 6
    That's not how `++` works. What's wrong with `+1`? – J. Holmes Jul 14 '13 at 16:54
  • 1
    Well, no ++ for function calls... – DerWaldschrat Jul 14 '13 at 16:54
  • @32bitkid : nothing wrong, just testing stuff here. – Akheloes Jul 14 '13 at 16:56
  • A cleaner way to do it would be: `$('#TextBox').val(function(){ return parseInt(this.value, 10)+1; });` – Joe Jul 14 '13 at 16:56
  • If you want to have some `+` signs together in a confusing way that works, do it like this `1 + + "5"; // 6` – Paul S. Jul 14 '13 at 16:57
  • take a look at [this](http://stackoverflow.com/questions/3709866/whats-a-valid-left-hand-side-expression-in-javascript-grammar) You're receiving this error in the console: `Reference Error: Invalid left-hand side expression in postfix operation` – kalley Jul 14 '13 at 16:57
  • Obviously you failed to research what `++` means. Please tell us, in detail, what you actually expected to happen. – Lightness Races in Orbit Jul 14 '13 at 17:23
  • @LightnessRacesinOrbit : I know what it means, I just couldn't see it for some reason, meaning once I got the answer I felt horrible. But I hope this is a good thread for beginners, maybe it'll help some of us. – Akheloes Jul 14 '13 at 17:27

3 Answers3

8

There's nothing particular to jQuery about this. ++ increments a variable. You are trying to increment the return value of a function call.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
4

Q: What does x++ mean?

A: x++ means take the value of x, let's call this n, then set x to be n + 1, then return n.

Q: Why does this fail on a non-variable?

A: Let's try it on something simple, say 3, and see where things go wrong.

  1. Take the value of 3 and call it n, okay, n = 3

  2. Set 3 to be n + 1, so 3 = 3 + 1, 3 = 4 this makes no sense! So if this step can't be done, the ++ operator can't be used.

Paul S.
  • 64,864
  • 9
  • 122
  • 138
0

++ works on variables, not directly on numbers

var c = parseInt($('#TextBox').val());
$('#TextBox').val( ++c );

Change the order from

var x = 0;

var result = x++;

result // 0

To

var x = 0;

var result = ++x;

result // 1

Then it will evaluate ++ before retrieving the value.

BrunoLM
  • 97,872
  • 84
  • 296
  • 452