Try this. What you're looking for is an XOR conditional, to compare the booleans of each text field. Unfortunately, JavaScript does not have an XOR operator but you can work around this. Have a look at this, it details using a logical XOR in JavaScript. I applied this method to your form. Please, swap out the alert()
calls with whatever you want. If you intend to use this for more text fields, make sure you add them to the long if
statement.
function submitform() {
if ( (MyForm.FirstName.value != null || MyForm.LastName.value != null ||
MyForm.MemberNum.value != null || MyForm.PhoneNum.value != null ||
MyForm.Email.value != null) && !(MyForm.FirstName.value == "" &&
MyForm.LastName.value == "" && MyForm.MemberNum.value == "" &&
MyForm.PhoneNum.value == "" && MyForm.Email.value == "")) {
alert("Form is okay!");
return (true);
}
alert("You must enter at least one field!");
return (false);
}
table, table tbody { width:99%; }
tr { width:100%; }
td { width:49%;
padding:5px;
font-size:1.03em;
background-color:tan;
border:1px solid black;
}
input[type="text"] {
width:95%;
font-size:1.03em;
}
button {
background-color:#dd0307;
border:2px solid white;
color:white;
padding:8px;
font-size:1.07em;
}
<form name="MyForm">
<table><tbody>
<tr><td> First Name: </td><td><input type="text" name="FirstName" /></td> </tr>
<tr><td> Last Name: </td><td><input type="text" name="LastName" /> </td></tr>
<tr><td> Member Number: </td><td><input type="text" name="MemberNum" /> </td></tr>
<tr><td> Telephone: </td><td><input type="text" name="PhoneNum" /> </td></tr>
<tr><td> Email: </td><td><input type="text" name="Email" /> </td></tr>
</tbody></table>
<button onclick="return submitform();">Submit</button>
</form>
The JavaScript MyForm
object comes from the HTML, <form name="MyForm">
. And each field can be accessed with MyForm.FirstName
, MyForm.LastName
, etc.