Jump to content

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


hitman47
Go to solution Solved by doddsey_65,

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!!!

Link to comment
Share on other sites

  • Solution
<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

Edited by doddsey_65
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.