Jump to content

how to keep the choosed data in the <select> element? HTML


hitman47

Recommended Posts

The user chooses his year of birth. This is stored in my mysql database. Easy.

<select name="year" >

 for ($year = 1960; $year <= 2030; $year++)  {
             echo '<option value="'.$year.'"><h4>' .$year.'<h4></option>';
       }

</select>

 

However when i hit submit the form resets to the first option of the list, in this example 1960. If the user chooses 2000 for example and hits submit, the valuse will be passed with post to the next php page, but when i return to this, his choise, 2000, is lost, and it will return to 1960.

 

How can i maintain his option in the select field? Furthermore i want if the user wants to change his option and the select field shows all the options from 1960 to 2030 in a row, not mixed. I am stuck. It is very frustrating. Help!!!

<select name="year" >
for ($year = 1960; $year <= 2030; $year++)  {
    if (!empty($_POST) && $_POST['year'] === $year) {
        echo '<option selected value="'.$year.'"><h4>' .$year.'<h4></option>';
    } else {
        echo '<option value="'.$year.'"><h4>' .$year.'<h4></option>';
    }
}
</select>

You need to check if there is post data and if the posted data matches the value of the option

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.