0

I want to run a loop. I want it to excecute it 16 times like,

for (var i = 0; i <= 15; i++) {  
 alert(i);  
} 

I want this loop to run on clicking a button. But the loop should only return the first value of i and then exit. Like this,

for (var i = 0; i <= 15; i++) {  
  alert(i);  
  exit();  
} 

What I am confused with is, whenever I click the button I want this loop to run-only once-but with the value being incremented by one. The whole idea is to alert the i value on each click of the button but incremented by one each time. I think even my use of for loop also is not making any sense. Or is my whole logic wrong. I think I am doing something more complex where something simple like using counter will accomplish the same. Any help appreciated.

Thomas Sebastian
  • 1,582
  • 5
  • 18
  • 38

4 Answers4

1
var myVal = 0;
function incrementValue(){
  myVal++;
  alert(myVal);
}

Just increment a variable every time you call the function.

TGH
  • 38,769
  • 12
  • 102
  • 135
1

If I am getting it right, it should be somewhat like this,

var btn_init = 0;

//on click 

$(function(){
   $('#your_button_id').on('click',function(){
      btn_init++; //increment
      alert(btn_init);
    }
});
Dimag Kharab
  • 4,439
  • 1
  • 24
  • 45
0
 <div class="button1">click</div>
  <div class="valuecontainer"></div>


  <script>
  var i=0;
  var x=15;
  $('.button1').click(function(){
  if(i<x){
  i++;
  $('.valuecontainer').html(i);
  }
 else
 {
 alert("rechaed limit");
 }

 });


 </script>
Katyoshah
  • 129
  • 10
0

I guess you will find your answer here: Count function call in JS

This is the shortest code found there though i donot completely understand this (somebody plz explain):

function myFunction() {
  this.num = (this.num || 0) + 1;
  if(this.num <= 15)
    alert(this.num);
} 
Community
  • 1
  • 1
Twaha Mehmood
  • 737
  • 3
  • 9
  • 26