I need to limit the number of check-boxes the user can check in a form that I have inside a php file.
I found the solution below on
http://www.javascriptkit.com/script/...boxlimit.shtml
which works just fine in case the name of the form input is something straightforward as 'countries' as below.
In my case the input name needs to be an array or say 'countries[]', which will fetch the user's input and post it to another php file via method POST.
When I change the input name to "countries[]" the script does not work. I am not at all good with JS so I am asking if somebody could tell me how to modify the script to work for my situation.
Thanks
<script type="text/javascript">
/***********************************************
* Limit number of checked checkboxes script- by JavaScript Kit (
www.javascriptkit.com)
* This notice must stay intact for usage
* Visit JavaScript Kit at
http://www.javascriptkit.com/ for this script and 100s more
***********************************************/
function checkboxlimit(checkgroup, limit){
var checkgroup=checkgroup
var limit=limit
for (var i=0; i<checkgroup.length; i++){
checkgroup[i].onclick=function(){
var checkedcount=0
for (var i=0; i<checkgroup.length; i++)
checkedcount+=(checkgroup[i].checked)? 1 : 0
if (checkedcount>limit){
alert("You can only select a maximum of "+limit+" checkboxes")
this.checked=false
}
}
}
}
</script>
<p>Select your favorite two countries below:</p>
<form id="world" name="world">
<input type="checkbox" name="countries" /> USA<br />
<input type="checkbox" name="countries" /> Canada<br />
<input type="checkbox" name="countries" /> Japan<br />
<input type="checkbox" name="countries" /> China<br />
<input type="checkbox" name="countries" /> France<br />
</form>
<script type="text/javascript">
//Syntax: checkboxlimit(checkbox_reference, limit)
checkboxlimit(document.forms.world.countries, 2)
</script>