JavaScript Allow Only 10 Checkbox Inputs to Be Submitted
The JavaScript code block below will allow only 10 checkbox inputs to be submitted. Checkbox is a type of HTML form input. It looks like this:
Want a Ford?
<input type="checkbox" name="cars" value="Ford"> Want a Ford?
The script will not only limit the user submissions to 10 checkboxes, it will also totally deal with the situation of users that submit more than 10 checkboxes: The arrays where checkbox names and values are stored will use the JavaScript slice() method to whittle themselves down to 10 values. Then the user will receive a JavaScript window alert() that reminds them of the number of inputs that will be allowed and then tells them that the 11th input and higher were discarded.
The code block begins with defining arrays. These will be populated by what is found in input tags of checkboxes that are marked as checked by being selected. The getElementsByTagName() method is now used to get the array of all the input tag objects' properties on the page. A for loop will now be used to loop through these objects, checking for which are marked checked which makes their checked property come out as true, when tested. These are the only objects we stick in our arrays. Unchecked objects are bypassed. Note that we get the name attribute and value attribute of the checked objects and populate our arrays.
We check if there has been more than 10 and use the slice() method to select a part of each array, and return a new array. We replace the old array with an array of the same name, using 0 and 10 as the start and end parameters. Then comes the alert. Finally, we use the JavaScript toString() method to stringify the arrays into 2 strings of comma-separated values and we stick these 2 strings into hidden form fields called fieldname and fieldvalue. Submitting the form sends all array values to a PHP processing script.
var x=0;var a=new Array();var b=new Array();
var e=document.getElementsByTagName("input");
for(var i=0;i<e.length;i++){
if(e[i].checked==true && e[i].type=="checkbox"){a[x]=e[i].name;b[x]=e[i].value;x++;
if(x>10){a=a.slice(0,10);b=b.slice(0,10);}}}
if(x>10){alert("Only 10 criteria, please. Your 11th through "+x+"th criteria were discarded.");}
if(x>0){document.formpw.fieldname.value = a.toString();
document.formpw.fieldvalue.value = b.toString();}