title: Limiting Checkbox Selection using JS and PHP
body: <p>We have a requirement to Limit the user Selection of a checkbox to a maximum. For example, we read different car models from a database and place them on a form for a user to select a maximum of two car models for further processing. we are using the following code segments (Sample codes Only):</p>
  
  <pre><code>&lt;script type="text/javascript"&gt;
  function KeepCount() 
  {   
      var total=0;
      for (var i=0; i &lt; document.car_form.model_selection.length; i++) 
      {
          if(document.car_form.model_selection[i].checked) {
              total =total + 1;
          }
          if (total &gt; 2) {
              alert('Pick Just One Please')
              document.car_form.model_selection[i].checked = false ;
              return false;
          }
      }
  } 
  &lt;/script&gt; 
  
  &lt;form action="car_model.php" method="post" name="car_form" id="car_form"&gt;
  
  &lt;?php
  $q10 = "SELECT ..."
  $r10 = mysqli_query ($dbc, $q10); 
  if (mysqli_num_rows($r10) &gt; 0) {    
      while ($row10 = mysqli_fetch_array($r10, MYSQLI_ASSOC)) 
      {
          echo '&lt;p class="normal_text"&gt;&lt;input type="checkbox" name="model_selection[]" value="' . $row10['model_id'] . '" onclick="return KeepCount()"; /&gt;' . $row10['car_model_name'] . '&lt;/p&gt;&lt;/br&gt;';
      }
  }
  ?&gt;    
  &lt;/form&gt;
  </code></pre>
  
  <p>This code however does not work as even if a user Selects more than 2 models, no warning is thrown. </p>