John the Painter
John the Painter

Reputation: 2615

Increase number in ID on click

If this has been answered already, please do point me in the right direction, but I'm trying to update the number at the end of an HREF of a link everytime it's clicked.

So, my link, for example is <a class="next" href="#slideshow-wrapper0">Next</a> and everytime it's clicked, I want it to update the '0' to '1' and then '2' and so on.

Any ideas? This is what I came up with...

$(document).ready(function(){
    var count = 0;
    $("next").click(function(){
       $(".work-main-content").append("<div id='portfolio-slideshow'" + (count++) +">");
    });
})

Cheers, R

Upvotes: 1

Views: 793

Answers (3)

Ram
Ram

Reputation: 144669

Try this:

$('.next').click(function(){
    $(this).attr('href', function(){
      var n = this.href.match(/\d+/);
      return '#slideshow-wrapper' + ++n
    })
})

Update:

$('.next').click(function(){
    $(this).attr('href', function(){
      var n = this.href.match(/\d+/);
      if (n > 20) {
          return '#slideshow-wrapper' + ++n 
      } else {
          return '#slideshow-wrapper0'
      }
    })
})

http://jsfiddle.net/rV663/

Upvotes: 2

sajawikio
sajawikio

Reputation: 1514

Use an object to keep track of it and increment it.

var c = {
   curr : 0,
   incrm: function(){this.curr++}
   }

 $("next").click(function(){
       $(".work-main-content").append("<div id='portfolio-slideshow" + c.curr +"' >");
       //use below to update href or what not
       $("#whatever").attr('href','portfolio-link-number-' + c.curr);
       c.incrm();

    });

Upvotes: 2

Prog Mania
Prog Mania

Reputation: 624

you are closing the id attribute before adding the count value

$(document).ready(function(){
    var count = 0;
    $("next").click(function(){
       $(".work-main-content").append("<div id='portfolio-slideshow" + (count++) +"' >");
    });
})

Upvotes: 2

Related Questions