Validation - check to make sure at least one field is filled out

Hello all!

I have developed a search form that allows any form element (or mutiplie form elements) to be filled in to conduct the search. However, I want the user to be required to fill out at least ONE form element before they hit Submit.

I have found many scripts that “require” a form element, but I want to build a script that only requires ANY form element (not a specfic one).

I have done fine with typical text boxes, but I am stumped when it comes to a Checkbox or a Drop Down.

First, here is my js code for the form check:

<script language="JavaScript"> <!--
function anyvalidate() {
if (       form.box1.value == ""
	&& form.box2.value == ""
	&& form.box3.value == ""
	&& form.box4.value == ""
	&& form.box5.value == ""
	&& form.box6.value == "") {
alert( "You need to complete at least 1 field to conduct a search" );
     return false;
//--> </script>

Here is the form:

<form name="form" action="" onSubmit="return anyvalidate()" method="post">
    <input name="box1" type="text">
    <input name="box2" type="text">
    <input name="box3" type="text">
    <input name="box4" type="text">
    <input name="box5" type="text">
    <input name="box6" type="text">
    <input type="checkbox" name="ckbox7" value="1">
    <select name="drop8">
      <option> </option>
    <input type="submit" name="Submit" value="Submit">

Could you fine folks tell me how I would go about checking to see if the Checkbox has been filled out or the Drop Down menu selected?

I TRULY would appreciate any help :slight_smile:

Take care

For the checkbox, test its “checked” property. It will be true if the box is checked.

For the select control, test its “selectedIndex”. This property will be -1 if nothing is selected.

So, add to your if statement:

&& form.ckbox7.checked == false
&& form.drop8.selectedIndex == -1

I think that should do it.


I had to change the value of the selectedIndex to 0, but other than that your code was right on !!!

I really appreciate it. Thanks very much!

Merry Xmas :slight_smile:

You may want to test < 1 for the selection list since not all browsers automatically select the first entry in the list and so it would have a value of -1 in that instance.

felgall, I will try that tomorrow. Thanks for the tip.