How do I iterate through dynamically generated checkboxes?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
daveshoope
Forum Newbie
Posts: 8
Joined: Thu Aug 06, 2009 10:28 am

How do I iterate through dynamically generated checkboxes?

Post by daveshoope »

pls Im having some problems with what method to use for a PHP manipulation.

PROBLEM: I want to make a teacher register student subjects on a web page by selecting the checkbox for each subject b4 submitting (so only checked subjects are registered). I put a single checkbox in a repeat region (which means at runtime, you will have as many checkboxes as there are subjects in the subject table).

How do I iterate through each checkbox (when submitted), register the checked subjects and ignore the unchecked ones. (to simplify it, just echo the values of checked subjects to the screen).
User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: How do I iterate through dynamically generated checkboxe

Post by social_experiment »

If a checkbox is selected it's value will be available under $_POST['checkBoxName']. I'm not sure (because i've not done something like this before) if it would work if you gave each checkbox a similar name, example :

Code: Select all

<!-- have one for each option, just change the values for every instance of the checkbox -->
<input type="checkbox" value="X" name="checkBoxArray[]" />
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: How do I iterate through dynamically generated checkboxe

Post by Celauran »

social_experiment wrote:I'm not sure (because i've not done something like this before) if it would work if you gave each checkbox a similar name, example :

Code: Select all

<!-- have one for each option, just change the values for every instance of the checkbox -->
<input type="checkbox" value="X" name="checkBoxArray[]" />
This works fine and is how I would recommend doing it. You can then iterate over the $_POST['checkBoxArray'] array using a simple foreach loop.
daveshoope
Forum Newbie
Posts: 8
Joined: Thu Aug 06, 2009 10:28 am

Re: How do I iterate through dynamically generated checkboxe

Post by daveshoope »

I was initially having some difficulty using the list() function to iterate through the array, but I just got my way around it. Thanks yo all a million.
Post Reply