Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

client side form validation Array

Status
Not open for further replies.

styleBunny

Technical User
Jun 20, 2002
133
0
0
AU
Hi All,

I have this function to validate, whether a users has made a selection from a multiple selection list box.

Code:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
<script language="javascript">

function validateContactForm(form) {
		if (form.foo.length == 0) { 
			alert('Please select.'); 
			return false;
		}
}

</script>
</head>

<body>
<form name="contact" method="post" onSubmit="return validateContactForm(this);">

<select name="foo[]" size="5" multiple> 
	<option value="apples">Apples</option>
	<option value="oranges">Oranges</option>
	<option value="pears">Pears</option>
	<option value="grapes">Grapes</option>
	<option value="mangos">Mangos</option>
</select>
<br>
<input type="submit" name="btnSubmit" value="Submit"> <input type="reset" name="btnReset" value="Clear">
</form>
</body>
</html>

I can get the length value returned when the array is static, but when its a dynamic array, created inside a form I haven had any luck!

Thanks for looking,
sb.
 
I know that PHP uses [] for element arrays, but it's not valid HTML according to W3C, the people who write the standards.

Try this with what you have:

Code:
function validateContactForm(thisform)
{
var numselected = 0;
var selection = thisform.elements['foo[]'];
for (var si=0;si<selection.options.length;si++)
  {
  if (selection.options[si].selected)
    {
    numselected++;
    }
  }

if (numselected == 0)
  {
  alert('Please select at least one item.');
  return false;
  }
return true;
}

Lee
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top