View Full Version : array in form validation

06-24-2003, 07:29 PM

str = "username,password,newsletter";
var a = str.split(",");
function show(){
return false;
return true

<form name="reg">
username <input type="text" name="username">
<input type="submit" name="submit" value="submit" onclick="return validate()">

An alert should popup with the word "username" on it. However, this just submits and no alert. It's actually "document.reg.a[0].value" that doesn't evaluate to anything and a[0] is 'username'. I want for it to alert and the form not to submit if username is blank. solutions? Thanks.

06-24-2003, 07:37 PM
Think about it for a sec, if document.reg.username referes to the username field, then document.reg.a[0] tries to refer to the first a field. Since your form has no a field(s), you get an error.

You must use the elements collection here.
document.reg.elements[a[0]].valueThe elements collection + lookup operator (also called the hashtable) must receive a string. Since accessing a[0] returns 'username', then the above is essentially the same as
document.reg.elements['username']Which i also the same as
document.reg.usernameThere you go!

06-24-2003, 07:45 PM
ah ha! thanks!