I'm making a form where the user can RSVP for themselves and up to 5 others. Each guest has a text field for their names and then radio buttons (yes or no) as to whether they are attending or not. By default Guest 1 & 2 are displayed and then there is a button the user can click to add another guest up until guest #6.
Guest's 3 - 6 are contained in their own objects like this:
var guestThree = {
name : document.querySelector('label[for="nameOfThirdGuest"]'),
attendingYes : document.querySelector('label[for="guestThreeAttendingYes"]'),
attendingNo : document.querySelector('label[for="guestThreeAttendingNo"]')
};
var guestFour = {
name : document.querySelector('label[for="nameOfFourthGuest"]'),
attendingYes : document.querySelector('label[for="guestFourAttendingYes"]'),
attendingNo : document.querySelector('label[for="guestFourAttendingNo"]')
};
var guestFive = {
name : document.querySelector('label[for="nameOfFifthGuest"]'),
attendingYes : document.querySelector('label[for="guestFiveAttendingYes"]'),
attendingNo : document.querySelector('label[for="guestFiveAttendingNo"]')
};
var guestSix = {
name : document.querySelector('label[for="nameOfSixthGuest"]'),
attendingYes : document.querySelector('label[for="guestSixAttendingYes"]'),
attendingNo : document.querySelector('label[for="guestSixAttendingNo"]')
};
I am hiding guest's 3 - 6 using the following function which are then converted to methods for the above objects:
function hideFields() {
this.name.style.display = "none";
this.attendingYes.style.display = "none";
this.attendingNo.style.display = "none";
}
I also have the opposite of the above function in showFields:
function showFields() {
this.name.style.display = "block";
this.attendingYes.style.display = "block";
this.attendingNo.style.display = "block";
}
So the idea here is that when the add guest button (which is assigned to the variable addGuest) is clicked guest #3 will be added. Then when it's clicked again guest #4 will be added and so on until #6. I've added the guestThree - guestSix objects to the following array:
var extraGuests = [guestThree, guestFour, guestFive, guestSix];
and then using the following for loop:
for (var guest = 0; guest < extraGuests.length; guest++) {
addGuest.onclick = function() {
extraGuests[guest].showFields();
};
}
But this doesn't work. I have discovered through testing that guest loops all the way round to 4 without executing the showFields methods. If I was to add a break after the onclick event then guestThree will display but that's it (obviously because that's how break works) but this atleast shows that the loop works as I hoped - to an extent.
So what I am asking of you guys is - what am I doing wrong? How do I make it so that the guest variable doesn't loop straight to 4? I need each iteration to be 0, 1, 2 and finally 3 and as far as I can see that is exactly what should be happening?
Cheers!