How to show selected option value after submit

血红的双手。 提交于 2019-12-14 03:32:20

问题


I have an html select that is populated with data from a query using a foreach loop. The default value is empty, so when the page loads, it displays an unfiltered query. It looks something like this

$client = $wpdb->get_results("SELECT string FROM `file` WHERE 
`code` = 001");

echo 'Filter by client: ';
  echo '<select name="client_list"><option value=""></option>';
  foreach ($client as $key => $row) {
    $value = $row->string;
    echo 
  '<option value='.$value.'>'
  .$value. '</option>';
  }
  $client = $_GET['client_list'];
  echo '</select>'; 

It serves as a filter to display data based on the selected option value. The table that it filters looks something like this

   |client  | file              | 
   |------  |-------------------|
   |client1 | file00000         |
   |client2 | file00002         |

Now when I hit submit and see the filtered query results which are correct, I also see the default option value instead of the one selected to filter the data in the html select. How can I fix this?


回答1:


Retain the value from your $_POST var and then add the selected attribute to retain and have it set to that selected value:

echo 'Filter by client: ';
  echo '<select name="client_list"><option value=""></option>';
  foreach ($client as $key => $row) {
    $value = $row->string;
    if($_GET['client_list'] == $value){ 
       echo '<option value='.$value.' selected>'.$value. '</option>';
    }else{
       echo '<option value='.$value.'>'.$value. '</option>';
    }
  $client = $_GET['client_list'];
  echo '</select>'; 


来源:https://stackoverflow.com/questions/46588904/how-to-show-selected-option-value-after-submit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!