I am trying to ensure that all fields of a form are not empty. When there are empty fields this alert comes up as expected, however when all fields are full the alert still comes up. Am I missing something?
var sn = document.myForm.address.length;
var sna = document.myForm.street.length;
var su = document.myForm.city.length;
var st = document.myForm.state.length;
var usn = document.myForm.username.length;
if (sn || sna || su || st || usn == null) {
alert("All fields are required. Please ensure you leave no fields blank.");
return false;
} else {
}
Since you initialized all your variables, your if
statement is evaluating true like this:
if (true || true || true || true || true || false)
Only one true
makes the entire if
condition above evaluate to true
because all the ||
operators are OR
operators.
Consider further, if you simply declare but do not initialize a variable for example var sn; //declared
var sn; //declared
as opposed to var sn = document.myForm.address.length; //initialized
var sn = document.myForm.address.length; //initialized
then its condition evaluates to false
because if(sn)
is declared but not initialized = false`.
Moreover, to check the value inside each variable rather than whether or not they are initialized, you must do this:
if (sn == null || sna == null || su == null || st == null || usn == null)
or possibly since you're assigned a length you want this
if (sn > 0 || sna > 0 || su > 0
etc...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.