1

I want to keep selected values after form submission, as suggested here by @ignacio-vazquez-abrams. I tried this:

<form action="" method="get">
    ...
    foreach ($file_array as $location)
        $options .= '<option name="' . $location . (($_GET['name'] == $location) ? 'selected="true"' : '') . '" value="' . $location . '">' . $location .'</option>';
    $select = '<select id="location" name="location">' . $options . '</select>';
    echo $select;
    ...
</form>

but I got a notice:

Notice: Undefined index: name in ...

UPDATE

Than I tried this (as was suggested in comments and I how is recommended here):

$options .= '<option name="' . $location . (!isset($_GET['selected']) ? 'selected="selected"' : '') . '" value="' . $location . '">' . $location .'</option>';

with no errors, but the expected result still has not been produced - selected values after form submission are not retained.

How to achieve this?

Community
  • 1
  • 1
Yurié
  • 2,148
  • 3
  • 23
  • 40

2 Answers2

1

You are using a strict mode of PHP, therefore you need to check if the GET param is passed (by using isset()) before comparing its value to something.

<form action="" method="get">
    <select id="location" name="location">
        <?php foreach($file_locations as $location): ?>    
        <option <?php echo ((isset($_GET['location']) && $_GET['location'] == $location) ? 'selected="selected"' : '') ?> value="<?php echo $location ?>"><?php echo $location ?></option>
        <?php endforeach; ?>
    </select>
</form>

Also you need to write selected="selected" or just selected instead of selected="true".

divix
  • 1,265
  • 13
  • 27
1

There's a whole lot missing to actually adding a right answer for this, but i'll try anyway.

PHP locations array:

$locations = array( 'Loc1', 'Loc2', 'Loc3' );

On the form:

<form action="" method="get">
    <select name="location">
        <?php 
            foreach ( $locations as $location ) {
                echo '<option value="' . $location . '" ' . ( isset( $_GET['location'] ) && $_GET['location'] == $location ? 'selected="selected"' : '' ) . '>' . $location . '</option>';
            }
        ?>
    </select>
</form>

First of all there's no way of telling that your posted value is the value name. As i recall there's no name attribute for option, it has to be a select around it which holds the attribute name, and you are putting the selected="true" in the name attribute which you are not properly closing in the first place (and which is non existing).

Wolfeh
  • 402
  • 2
  • 6
  • Sorry! I updated the question with the missing data, but you guessed it anyway. In the future questions I will be more careful and I will include all necessary information. Now the code is working as was expected! Thank you very much? – Yurié Nov 26 '15 at 12:13
  • another approach using `js` - https://stackoverflow.com/a/16458797/4050261 – Adarsh Madrecha Dec 05 '17 at 08:53