Page 1 of 1

How do I iterate through dynamically generated checkboxes?

Posted: Tue Aug 30, 2011 4:01 am
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).

Re: How do I iterate through dynamically generated checkboxe

Posted: Tue Aug 30, 2011 5:06 am
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[]" />

Re: How do I iterate through dynamically generated checkboxe

Posted: Tue Aug 30, 2011 6:52 am
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.

Re: How do I iterate through dynamically generated checkboxe

Posted: Tue Aug 30, 2011 9:41 am
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.