getaway
getaway

Reputation: 8990

Increasing a number by 1 using jquery?

$('.fav').live('click', function(e){
    $(this).toggleClass('highlight');
    //increase the number by 1

html:

<li class="fav light_gray_serif">5</li>

how can i use jquery to increase the number between the li everytime its clicked? thanks

Upvotes: 2

Views: 20683

Answers (4)

diazdeteran
diazdeteran

Reputation: 1194

HTML:

<span id="counter">0</span>

jQuery:

$('#counter').text(Number($('#counter').text())+1);

You can increase the counter when clicking an existing button like this:

$(document).on('click','#your-button', function(){
  $('#counter').text(Number($('#counter').text())+1);
});

Upvotes: 3

Raynos
Raynos

Reputation: 169391

Just use a plugin.

(function($) {
    $.extend($.fn, {
         "addOne": function() {
              var num = parseInt(this.text(), 10);
              this.text(++num);
         },
         "subtractOne": function() {
              var num = parseInt(this.text(), 10);
              this.text(--num);
         }
    });
}(jQuery))

Then call

$(".fav").live("click", function(e) {
     $(this).toggleClass("highlight").addOne();
});

Upvotes: 1

The Scrum Meister
The Scrum Meister

Reputation: 30111

var num = parseInt($.trim($(this).html()));
$(this).html(++num)

Upvotes: 12

PleaseStand
PleaseStand

Reputation: 32082

You want to take a look at .html() or .text(). Here is an example:

$(this).text(function(i, t) {
    return Number(t) + 1;
});

Upvotes: 6

Related Questions