[thelist] js testing for empty fields

Ben Dyer ben_dyer at imaginuity.com
Thu Feb 13 15:28:01 CST 2003

At 03:05 PM 2/13/2003, you wrote:
> > you could also just check for:
> >
> >     if(myForm.elements['myField'].value) { doSomething() }
> >
> > assuming your form was anything but boolean
>Well, if the user enters 0 (zero) then the above if expression would
>evaluate as false in JavaScript, even though the user indeed entered data,
>so I wouldn't actually recommend this. :)

Actually, I don't think that's true.  I just whipped up a quick test.

<script language="JavaScript">
         function test() {
                 if (!document.forms[0].elements[0].value) {
                         alert("test IS false");
                         return false;
                 } else {
                         alert("test IS true");
                         return false;

<form method="post" action="anything.html" onsubmit="return test()">
<input type="text" name="testField" id="testField" size="15" value="" /><br />
<input type="submit" name="Submit" value="Submit" />

When you submit, the only time the alert "test IS false" came up was when
there was no value in the text field.  A value of "0" correctly returned
the "test IS true" box, as did anything else I entered: "1", "false", "Rei
Ayanami", etc.

I only tested IE6/W2K, but I've never heard of it being the case to return
false when the form field value is 0.  Perhaps I'm misunderstanding what
you're suggesting.


More information about the thelist mailing list