Skip to content
Advertisement

Ignore empty form fields when sending PHP

I’m fairly new to PHP so I understand enough to get myself confused, but not enough to accomplish anything productive. I have a sign-up form that allows the user to add up to five students. The form fields for each student is wrapped in their own div class (.student1, ,student2, .student3, .student4, and .student5). I’m trying to prevent the PHP code from sending data if all the fields in the wrapped div classes are left blank.

Example 1: If the user fills out information for two students (.student1 and .student2), only email those two students and prevent the other three from sending. Example 2: If the user fills out only partial information for a student, still send ALL fields for that student to email and ignore the other students that are entirely empty.

I would be ok with implementing code that ignored ALL empty form fields from the entire form but I would rather only apply the rule to all fields within a div. Is that even possible!?

Here is my code:

JavaScript

Advertisement

Answer

You can actually simplify a lot of what you have. Remember, keep it DRY (don’t repeat yourself).
Also, I am checking for empty values so you don’t get errors for undefined indexes as well as giving a default value if it isn’t there.
On top of that, trimming everything so you aren’t left with a bunch of spaces before/after anything

Instead of creating 30 variables (6 for each student), create 1 array, then loop through the array at a later time. Helps keep it expandable in the future if you want to add more fields or students to your form.

The only time a student’s info isn’t added to a form, is when ALL fields are empty. If 1 only 1 is used, give a default to the others, if they are empty.

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement