Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery increment value of <span> tag

Tags:

jquery

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");
like image 307
user978905 Avatar asked Oct 08 '11 18:10

user978905


3 Answers

Example -

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

$('.changeNumber').html(parseInt($('.changeNumber').html(), 10)+1)
like image 139
Jayendra Avatar answered Nov 09 '22 04:11

Jayendra


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()
like image 27
Only Bolivian Here Avatar answered Nov 09 '22 02:11

Only Bolivian Here


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);
like image 7
Jess Avatar answered Nov 09 '22 04:11

Jess