1

So I've got a span that goes like this:

 <span>1</span>

Now I want to do something like this (plus it)

 $(this).next("span").text($(this).next("span").text + 1);

But it won't work. You're seeing where I'm going though, right? I want to make the number in the string or variable go one higher.

How can I do that?

2
  • 2
    You should accept an answer if you found one helpful :) Commented Oct 12, 2012 at 20:57
  • I will, I just can't accept one in 5 minutes, just posted another question ;) Commented Oct 12, 2012 at 20:58

2 Answers 2

6
$('span').html( parseInt( $('span').html(),10 ) + 1 );

jsFiddle example

Sign up to request clarification or add additional context in comments.

3 Comments

@Schart If this answer solved your problem you should accept it by clicking the outlined checkmark below the down arrow.
@Schart: The main thing to realise here, is that, unlike PHP (which I presume you are coming from, given the $nexttext thing in your example comment) - JS does not automatically convert variables from text to numbers, you have to do so manually using a set of conversion functions, of which parseInt() is one, parseFloat() is another.
Okay good to know! :) (I haven't accepted yet because I had to wait 5 minutes before accepting another answer)
4

Try the JavaScript parseInt() function. Be sure you properly handle error cases, as in someone putting an invalid integer value into the span.

3 Comments

I tried : '$nexttext = parseInt($(this).next("span"));' and then '$(this).next("span").text($nexttext + 1);' but it didn't work. It returns NaN
@Schart $nexttext doesn't contain text, but an object. That is why it didn't work.
Okay. Thanks for the parseInt thing though, it will definitely help in the future! :)

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.