2

I'm trying to add one to a number inside a p element with jQuery, but it doesn't work.

$(document).ready(function() {
            function addOne() {
                var number  =   $('p').html();
                return number++;
            }

            $('p').text(addOne());
        });
1
  • Are you getting incorrect results or no results at all? If you're not getting any results, check the Error Console (in Firefox), as there may be something else going on. If you're getting results, but wrong results, post them here-- that way we can better understand the issue.
    – Blank
    Mar 26, 2010 at 1:28

3 Answers 3

5

You need to parse the number as an Int first, otherwise JavaScript is going to treat it like a string and concatinate it instead.

Also, you want your function to return number + 1, or at least ++number, otherwise you're incrementing after returning, and not actually getting the modified value.

Try this:

$(document).ready(function() {
    function addOne() {
        var number  =   parseInt($('p').html());
        return number + 1;
    }
    $('p').text(addOne());
});
1
  • I assume this is test code as well? Because that code will break violently if there are multiple <p> tags in the source-- you should really be using an id="something" in the markup and a matching $('p#something') in jQuery.
    – Blank
    Mar 26, 2010 at 1:24
3

Try this instead:

$(function(){
  $('p').html(function(i, currentHTML){
    return +currentHTML + 1;
  });
});

The original code had two bugs:

  1. The HTML needed to be parsed as an integer. The proper way to do this is with parseInt(html, 10) (parse as a base-10 integer). The shorthand way, if you know what the HTML contains, is +html.

  2. The addOne function returned number++, when it should really return number + 1 or ++number. (The latter example increments number before returning it.)

The corrected code above uses new .html() syntax in jQuery 1.4 (documentation). If you're using jQuery 1.3.x or older, you can use the older .html() syntax with the noted bugs fixed:

$(function(){
  function addOne(){
    var number = +$('p').html();
    return number + 1;
  }
  $('p').html(addOne());
});
1
  • 1
    ...oh wow, I totally missed the ++ issue. ^_^ I'll edit my example as well.
    – Blank
    Mar 26, 2010 at 1:29
0

Try adding parseInt:

var number = parseInt($('p').html());

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.