Reputation: 5737
Using select and option HTML tags, I pass information through using $_POST.
When reloading the page however, the select resets back to the original values. I am looking to get it to remember what has been passed through.
<?php
foreach($data as $value => $title)
{
foreach($ag as $first)
{
foreach($af as $second)
{
echo"<option value='$value-$first-$second'>$title - $first - $second</option>";
}
}
}
?>
As you can see, I use 3 foreach loops to populate whats in it. How can I achieve my selection being remembered?
Thanks for reading.
Upvotes: 0
Views: 807
Reputation: 19309
You'll need to use the name of your select
field in place of "your_select_field_name
" in my change below:
<?php
foreach($data as $value => $title)
{
foreach($ag as $first)
{
foreach($af as $second)
{
echo "<option value='$value-$first-$second'";
if( $_POST['your_select_field_name'] == "$value-$first-$second" ) {
echo ' selected="selected"';
}
echo ">$title - $first - $second</option>";
}
}
}
?>
Upvotes: 2
Reputation: 12243
You need to set the selected tag on the correct option. Something like this:
<?php
$postedValue = $_POST['select_name'];
foreach($data as $value => $title)
{
foreach($ag as $first)
{
foreach($af as $second)
{
$computedValue = $value . '-' . $first . '-'. $second;
if ( $computedValue == $postedValue) {
$selected = "selected";
} else {
$selected = ''
}
echo "<option value='$computedValue' $selected>$title - $first - $second</option>";
}
}
}
?>
It could probably be written cleaner but this is the general idea.
Upvotes: 0
Reputation: 146450
HTML does not have memory. The item that's selected by default in a <select>
form element is the one with the selected
attribute (or the first one if none). Simply use the information contained in $_POST to generate the appropriate markup:
<select name="foo">
<option value="v1">Label 1</option>
<option value="v2">Label 2</option>
<option value="v2" selected="selected">Label 3</option>
<option value="v4">Label 4</option>
</select>
Upvotes: 1
Reputation: 138042
The output for the selected option on the new page needs to look like:
<option value='foo' selected>...<option>
Upvotes: 1