Reputation: 227
I have a form where the user needs to put in all the people who are attending:
Person 1
Name
DOB
Email
Person 2
Name
DOB
Email
I need to work out each person's age and make sure at least one person is over the age of 16 to attend.
I get all the date of birth select field years and do the calculations to return each person's age.
I can then do an if statement age <= 16
to return if the argument is true or not.
My issue is here.
I need to check if ALL people are under 16, not single items.
Basically, if ALL people are under the age of 16 display an alert else if one person is over 16 don't do anything.
I don't know if I can expand on what I have to achieve this or to do some type of array mapping? I have looked at array mapping but not with the added age calculation I need to do.
Your help/advice is greatly appreciated (ES5 below please).
const checkAllAges = document.querySelectorAll("[data-dob='dobYear']");
function checkAge() {
for (const item of Array.from(checkAllAges)) {
const selectedYearValue = item.value;
const currentYear = new Date().getFullYear();
const age = currentYear - selectedYearValue;
console.log(item)
console.log(age)
if(age <= 16) {
console.log("one of the values is less than 16");
}
if(age > 16) {
console.log("one of the values is greater than 16");
}
}
}
for (const item of Array.from(checkAllAges)) {
item.onchange = function(){
checkAge();
};
}
Below is what my console returns from "item","age" and age check if that helps:
Upvotes: 0
Views: 241
Reputation: 66
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every
or
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some
let isUnder16 = Array.from(ages).every(function(age) {
return age < 16;
});
let isBigger16 = Array.from(ages).some(function(age) {
return age > 16;
});
Upvotes: 3
Reputation: 2137
This should help. Replace you code with this sample:
const checkAllAges = document.querySelectorAll("[data-dob='dobYear']");
const currentYear = new Date().getFullYear();
if (Array.from(checkAllAges).every(({ value }) => (value - currentYear) < 16)) {
console.log('Everyone is under 16');
}
Upvotes: 2