April 26, 2012

eval addition with -1 doesn't work

Question by David 天宇 Wong

I’m having trouble with this js code:

$('.downvoted').live('click',function(){
var ele = $(this);
var truc = ele.prev('.score_position');

$.post('ajax/vote.php', { vote :ele.attr('title') }, function(data) {
    if(data == 'done'){
        ele.removeClass('downvoted').addClass('downvote').html('<img src="images/down.png" />');
        truc.html(eval(truc.html()+1));
    }
});
return false;
});                 

so I have this same function 3 other times for downvoting, un-upvoting and upvoting. It works well except with one exception, if truc.html() is -1 then it goes to -11 instead of 0.

Any idea why it doesn’t work? (you guys can try it here: http://91.121.154.130/?sort=last&# with id:azerty pw:azerty)

Answer by Elliot Bonneville

Don’t use eval() for this sort of work! Use parseInt, Number(...), or any of the other numerous ways of converting a value to a number in Javascript.

truc.html(parseInt(truc.html(), 10) + 1);

Note the second parameter in the parseInt function. This means you want the value passed into be parsed as a base-10 number. If you pass in a number starting with 0 into the parseInt function without specifying the radix you’ll get an unexpected and unwanted result.

Or

truc.html(Number(truc.html())+1);

Or even this:

truc.html(truc.html()*1 + 1);

This works because multiplying a string number by one results converts the variable to a number. Be careful– if the variable you multiply isn’t a valid number you’ll get NaN!

The reason you can’t simply do truc.html(truc.html()+1); is because .html() returns a string value. If you add a number to a string in Javascript, the number is simply concatenated to the string, and no math is performed. (e.g. “-1” + “1” equals “-11”).

Answer by Starx

You need to make sure the value is an integer and Use of .text() is better on this case.

parseInt(truc.text(), 10)+1

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!