user2421594
user2421594

Reputation: 81

Run a For loop then stop

I want to click on this button and every time the button is clicked, 1 is added but when it gets to 12 I would like it to stop no matter if you continue to click on the button. Here is what I got so far.

<button>Click Me</button>

<script>
    $(document).ready(function(){
        $('button').click(function(){
            for ( var i = 0; i <= 12; i = i + 1 ) {
                console.log(i.val()+1);
            }
        });
    });
</script>

Upvotes: 0

Views: 67

Answers (5)

VIDesignz
VIDesignz

Reputation: 4783

var t=0;
$('button').click(function(){
     if(t++>=12){              
       return true;
    }
});

Upvotes: 0

Krish R
Krish R

Reputation: 22711

Try this,

$(document).ready(function(){       
    var t=0;
    $('button').click(function(){
        t = t+1;
        if(t>12){              
           return true;
        }
        console.log(t);

    });
});

DEMO: http://jsfiddle.net/z8m7d/

Upvotes: 0

MRaja
MRaja

Reputation: 1

Best way is, once you reach 12 count then DISABLE the Button. So, user will not be able to click it after 12....

Upvotes: 0

Ram Mehta
Ram Mehta

Reputation: 519

You need to put a break point as follows :

 $('button').click(function(){
    for ( var i = 0; i <= 12; i++ )
    {
           if(i==12)
             {
       break;  // breaks out of loop completely
             }
        console.log(i);
    }
});

This would totally throw the code out of the for loop when the value comes to 12.

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

like

jQuery(function () {
    var counter = 0;
    $('button').on('click.counter', function () {
        if (++counter == 12) {
            $(this).off('click.counter')
        }
        console.log(counter)
    })
})

Demo: Fiddle

Upvotes: 4

Related Questions