mercredi 24 avril 2019

How to get if checkbox is checked or not

So I have to make this soccer website where theres a list of checkboxes (i the registration) to select the prefered position. I want, for example, when someone inputs the center-attack checkbox and the goalie checkbox, to send me a list of the positions selected. As you can see, it's a picture with a list of checkboxes fo every position

The checkboxes layout

So i used this code to see if the checkbox in question is selected (duplicated for every checkbox/position):

if (document.getElementById("goalie").checked == true) {
    var Goalie = "Goalie";
};

Then, I combine all the strings with:

PreferedPositions = Goalie + " " + LeftDefense + " " + CenterLeftDefense + " " + CenterRightDefense + " " + RightDefense + " " + LeftMidfield + " " + CenterMidfield + " " + rightmidfield + " " + LeftAttack + " " + CenterAttack + " " + RightAttack + ".";

And I send it to php so I can email it to the owner with ajax:

$.ajax({
      type: "POST",
      url: "registration.php",
      data: {
            PostPreferedPositions: PreferedPositions
      },
success: function (res) {}
});

But when I test it out, the email comes out with:

"Prefered positions: undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined undefined."

I understand all the undefined if I had selected none of the checkboxes. But this occurs no matter how many checkbox I have selected. Like if I had the goalie and center-attack selected, I would expect:

"Prefered positions: Goalie undefined undefined undefined undefined undefined undefined undefined undefined Center-Attack undefined."

But that's not the case. I know I can easily fix all the undefined by putting a else if in the statement, but I don't know why all the positions return as undefined.




Aucun commentaire:

Enregistrer un commentaire