Validating multiple checkboxes


Apologies if this is a duplicate thread, though I did search existing topics but couldn’t find a similar problem to mine.

I have some checkboxes in a form that I’d like to validate (check to ensure that at least one has been ticked):

<input type="checkbox" name="response[]"  value="answer1"  />answer1
<input type="checkbox" name="response[]"  value="answer2"  />answer2
<input type="checkbox"  name="response[]"  value="answer3"  />answer3
<input type="checkbox"  name="response[]"  value="answer4" />answer4

The javascript below only works if I change my checkbox names to name=“response” rather than name=“response”.

function validateform()
	var success = false;

	for (i = 0; i < document.surveyform.response.length; i++)
		if (document.surveyform.response[i].checked)
			success = true;

	return success;

I need to pass along multiple checkbox responses to my PHP script and therefore need to keep checkboxes named name=“response”. When I do this, I get the error “document.surveyform.response has no properties”

Any idea what change I can make to the javascript so that I can name my checkboxes name=“responses” ?

Any help would be appreciated.


This is where you use an associative array.

//for (i = 0; i < document.surveyform.response.length; i++)
for (i = 0; i < document.surveyform.elements['response[]'].length; i++)
	//if (document.surveyform.response[i].checked)
	if (document.surveyform.elements['response[]'][i].checked)

Here is how I might choose to recode the above function:

<form id="surveyform" ...>

And have this at the end of the body, just before the </body> tag:

var form = document.getElementById('surveyform');
form.onsubmit = validateForm;

function validateForm() {
	var isValid = false,
		form = this,
		els = form.elements['response[]'];
	for (i = 0; i < els.length; i += 1) {
		if (els[i].checked) {
			isValid = true;
	return isValid;

pmw57, thanks very much for your help, that works great :slight_smile: