Reputation:
How do I to ensure that all the elements that are matched by the selectors in the keys of an object have a non-blank value? Mainly just trying to avoid too many arguments inside an if statement.
I've tried:
var credit_map = {
"#first": "First Name",
"#middle": "Middle Name",
"#last": "Last Name",
"#email": "Email Address",
"#postalcode": "Zip/Postal Code",
"#card_name": "Name on Card",
"#card_number": "Card Number",
"#card_month": "Card Experation Month",
"#card_year": "Card Experation Year",
"#card_verification": "Card Verification Code"
}
for (var [key, value] of Object.entries(credit_map)) {
if ($(key).val() != null || undefined) {
}
}
Upvotes: 0
Views: 72
Reputation: 1074425
I think you're asking how to ensure that all of the elements that are matched by the selectors in the keys of your object have a non-blank value. If so, you can use every
:
if (Object.keys(credit_map).every(sel => $(sel).val())) {
// Yes, they all have non-blank values
} else {
// No, at least one of them has a blank value (or didn't exist at all)
}
That works because both ""
and undefined
are falsy values, and all non-blank strings are truthy. every
converts the return value to boolean and uses it as a flag.
Upvotes: 1