Advertisement
myapit

JS Multiselect checkbox limit PHP Supported

Apr 5th, 2017
390
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <script type="text/javascript">
  2.  
  3. /***********************************************
  4. * Limit number of checked checkboxes script- by JavaScript Kit (www.javascriptkit.com)
  5. * This notice must stay intact for usage
  6. * Visit JavaScript Kit at http://www.javascriptkit.com/ for this script and 100s more
  7. ***********************************************/
  8.  
  9. function checkboxlimit(checkgroup, limit){
  10.     var checkgroup=checkgroup
  11.     var limit=limit
  12.     for (var i=0; i<checkgroup.length; i++){
  13.         checkgroup[i].onclick=function(){
  14.         var checkedcount=0
  15.         for (var i=0; i<checkgroup.length; i++)
  16.             checkedcount+=(checkgroup[i].checked)? 1 : 0
  17.         if (checkedcount>limit){
  18.             alert("You can only select a maximum of "+limit+" checkboxes")
  19.             this.checked=false
  20.             }
  21.         }
  22.     }
  23. }
  24.  
  25. </script>
  26.  
  27.  
  28. <p>Select your favorite two countries below:</p>
  29.  
  30. <form id="world" name="world">
  31. <input type="checkbox" name="countries[]" /> USA<br />
  32. <input type="checkbox" name="countries[]" /> Canada<br />
  33. <input type="checkbox" name="countries[]" /> Japan<br />
  34. <input type="checkbox" name="countries[]" /> China<br />
  35. <input type="checkbox" name="countries[]" /> France<br />
  36. </form>
  37.  
  38. <script type="text/javascript">
  39.  
  40. //Syntax: checkboxlimit(checkbox_reference, limit)
  41. //checkboxlimit(document.forms.world.countries, 2)
  42. checkboxlimit(document.getElementsByName('countries[]'),2); // to support PHP array data
  43. </script>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement