user978905
user978905

Reputation: 5517

jQuery increment value of <span> tag

I have a number in a span tag. I need to get the value of the number in the span and then increment it inside jQuery. I know how to do this for a text input - can this be done to a span tag?

SPAN tag

<span class="changeNumber"> 33 </span>

jQuery span selector

var commentNumAppend = $(this).closest(".songContainer").find(".changeNumber");

Upvotes: 18

Views: 26507

Answers (7)

Jess
Jess

Reputation: 25079

This is the most complete answer.

  1. This solution avoids selector repetition
  2. Handles the increment gracefully if the span does not have a value yet.
<span class="changeNumber"></span>
var $number = $('.changeNumber');
$number.html((parseInt($number.html(),10) || 0) + 1);

Upvotes: 7

Dipendra Kumar Mishra
Dipendra Kumar Mishra

Reputation: 311

$(".changeNumber").html(parseInt($(".changeNumber").html())+1)

Upvotes: 0

Only Bolivian Here
Only Bolivian Here

Reputation: 36743

You can do something like:

var value = parseInt($(".changeNumber").text(), 10) + 1;
$(".changeNumber").text(value);

JsFiddle Example:

http://jsfiddle.net/stapiagutierrez/WXAvS/1/

References:

  1. parseInt()
  2. text()

Upvotes: 20

Jayendra
Jayendra

Reputation: 52779

Example -

<span class="changeNumber">33</span>

$('.changeNumber').html(parseInt($('.changeNumber').html(), 10)+1)

Upvotes: 37

Rafay
Rafay

Reputation: 31033

var spanVal=$("span").html();
if(!isNaN(spanVal)){

alert("value incremented"+ (++spanVal));
}

http://jsfiddle.net/c84F4/

Upvotes: 1

Sparky
Sparky

Reputation: 15075

I assume you mean something like this?

<span id="Nbr">123</span>

If so, the InnerHTML property will give you the content of the span

Upvotes: 0

Matt Ball
Matt Ball

Reputation: 359816

Something like this:

var $span = $('#mySpanId');
$span.text(Number($span.text()) + 1);

http://jsfiddle.net/mattball/Cf834/

Upvotes: 2

Related Questions