Reputation: 21
there are a few questions like this on here, but what I am wanting to do is loop through every option element and echo them out, so far it is only echoing the selected item, when Ideally I am going to loop through each item.
<?php
if (isset($_POST['submit'])) {
$st_campaigns = $_POST['campaigns'];
foreach ($st_campaigns as $st) {
echo $st;
}
}
?>
<form action="" method="post">
<select name="campaigns[]" id="campaigns[]" size="15" multiple="multiple" style="width:150">
<option>item</option>
<option>item1</option>
<option>item</option>
<option>item</option>
<option>item</option>
<option>item</option>
<option>item</option>
</select>
<input type="submit" name="submit" />
</form>
Upvotes: 2
Views: 406
Reputation: 3385
You will need a workaround.
Add a hidden field in your form named "options" (for example)
On submit, use Javascript to loop through the items and generate a string. Comma separated or JSON might be a better option. So all options whether selected or not will be in the string.
Change the value of the hidden field (options) to the JSON string
When the form submits, use php to read $_POST['options']
instead of campaigns
, change JSON to array (or split csv depending on what you chose) and loop through that instead.
You can always match the selected items by first looping campaigns
and creating key values then using php array_key_exists
to see if key exists or in_array
if you simply add selected items to array.
Upvotes: 0
Reputation: 219874
Only the selected items are submitted with the form data. If you want all of the possible select items you will need to put them in an array and then you can use that array to populate/generate the select field as well as loop through them for whatever reason after the form is submitted.
Upvotes: 3