Validating and passing multiple drop down box selections

Hi,

I have a webpage with a form with a drop down selection list where the user can select multiple entries. (please see form below)

The user must select at least one entry and once having done so the details of the form are passed to a php script (mailform.php) and are formatted and processed.

What I can not work out is how to write the javascript code to validate that the user has selected at least one of the drop down list items and then pass the selected items a php script which can process the multiple items.

The code below passes the details perfectly to the script but does not validate that at least one entry item has been selected on the webpage because it does not seem to recognise document.forms[0].subject.length.

My HTML form code is as follows:

<form method="POST" name="contact" action="mailform.php" onSubmit="return validateform()">

.

.

.

<select size="10" name="subject[]" multiple>

<option value="Accredited Training">Accredited Training</option>

<option value="Advanced Management Qualification">Advanced Management Qualification</option>

<option value="Asian Business Qualification">Asian Business Qualification</option>

.

.

.

</select

<input type="submit" value="submit" name="B2">

My validation Javascript is:

<script language=“JavaScript”>

<!-- validate form fields

function validateform()

{

var count = 0;

for (var i = 0; i < document.forms[0].subject.length; i++)

{

if (document.forms[0].subject.options[i].selected)

{

count++;

}

}

if (count == 0)

{

alert(‘You must enter at least one value.’);

return false;

}

}

Within my PHP script I process the selection list (subject) as follows:

if (isset ($newsubjects)) {

foreach($newsubjects as $subdisplay) {

$body = $body .$subdisplay."
";

The php script works fine. Just the validation on the webpage does not work.

All I really want to do is to be able to validate that at least one selection item has been selected, pass it to a php script which can iterate through the field/array (subject) and format the items chosen.

Would really appreciate some guidance.

Would really appreciate some guidance.

Well, I got carpal tunnel syndrome in my fingers from scrolling down the length of your post, so my first piece of advice is: eliminate all the carriage returns.

My second piece of advice is to make #7 here:

a daily mantra.

What 7 said, with 1 thing to add.

You have no form element called subject. And if you did, it wouldn’t be an array it’d be a SELECT.
Here is your new function


function validateform() {
	if( document.forms[0].elements["subject[]"].selectedIndex == -1 ) {
		alert('You must enter at least one value.');
		return false;
	} else {
		return true;
	}
}