问题
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