I’m trying to increment values on button clicks. This is easy if there is only 1 button but I’m confused on how to keep track of the counts if there are multiple buttons. This seems even more challenging because I won’t know prior to page load how many button counts I have to keep track of. The ultimate goal is to build multiple AJAX pagination schemes on a single page (load older list items from my database sequentially and specific to the item that was click).
here’s the JSFiddle (below is its JS and HTML) i’ve started to get at this: http://jsfiddle.net/trpeters1/menAX/6/
JS:
var cnt=function(id){ //this code is incomplete but hopefully you'll get the idea of what i'm trying to do...
var j=0;
for(var i=0; i>100; i++){
if(id[i]==i) j+=5;
}
return j;
};
$('button').click(function(){
var id=this.id;
var c=cnt(id); //something which will return the current increment value of the button that was clicked
$('#'+id+'div').append(c+'message'+id+'<br>');
});
HTML:
<button type="button" id="btn1">1</button><div id="btn1div"></div>
<button type="button" id="btn2">2</button><div id="btn2div"></div>
<button type="button" id="btn3">3</button><div id="btn3div"></div>
The problem with this code is that clicking each of the buttons outputs the same message. Ideally, the code would be able to keep track of each button that was clicked. The way I was thinking this could work would be to tie each button’s id with its own counter (would probably need multiple j counters?).
thoughts?
You can store a counter against each button using jQuery’s
.data()method:Demo: http://jsfiddle.net/menAX/8/