By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
429,615 Members | 1,961 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 429,615 IT Pros & Developers. It's quick & easy.

Limit number of clicks

KeredDrahcir
100+
P: 426
I have a loop which draws a 12 x 8 grid of 96 squares. I'm using a JavaScript function so that if a user clicks on a square it changes to red and if they click on it again, it will change back to black.
What I want to do it prevent them from having more than 50 red squares at any one time.

I have a function that does this kind of think with checkboxes but I'm not sure how to do it with the grid I'm using. Can anyone help please?

JavaScript
Expand|Select|Wrap|Line Numbers
  1. <script type="text/javascript">
  2.   <!--
  3.     function plan(id){
  4.       var obj = document.getElementById(id);
  5.       obj.style.backgroundColor = (obj.style.backgroundColor == "rgb(0, 0, 0)") ? "#ff0000" : "#000000";
  6.      }
  7.   //-->
  8. </script>
Box (within loop)
Expand|Select|Wrap|Line Numbers
  1. <div style="width: 30px; height: 30px; border-style: solid; border-color: #ffffff; border-width: <?=$border;?>; float: left; background-color: #000000;" id="<?=$row, $column;?>" onclick="plan('<?=$row, $column;?>');">&nbsp;</div>
Aug 5 '13 #1
Share this Question
Share on Google+
4 Replies


Rabbit
Expert Mod 10K+
P: 12,359
A couple of ways to do this. Either loop through your divs and keep a count of how many of them are red or keep a running count whenever the function is called and decrement or increment appropriately.
Aug 5 '13 #2

Exequiel
100+
P: 287
Try this one. .
Expand|Select|Wrap|Line Numbers
  1. <script type="text/javascript">
  2.       <!--
  3.       var count=1;
  4.         function plan(id){
  5.  
  6.           var obj = document.getElementById(id);
  7.           if(count <= 5){
  8.               obj.style.backgroundColor = (obj.style.backgroundColor == "rgb(0, 0, 0)") ? "#ff0000" : "#000000";
  9.           }else{
  10.                alert('You reach the maximum click.  Total click: '+count);
  11.         }
  12.  
  13.           count++;//counter
  14.  
  15.          }
  16.       //-->
  17.     </script>
Aug 6 '13 #3

Rabbit
Expert Mod 10K+
P: 12,359
@exequiel, you need to start the count at 0. And you have no decrement. You need to decrement/increment appropriately otherwise the code stops working after any 5 clicks rather than after 5 red divs.
Aug 6 '13 #4

Exequiel
100+
P: 287
@Rabbit . okey, thank you for that comment. . really appreciated. . :)
Aug 6 '13 #5

Post your reply

Sign in to post your reply or Sign up for a free account.