正在检索列表中选定的元素

Retrieving the selected element in the list

本文关键字:元素 检索 列表      更新时间:2023-12-27

我有一个列表,它的元素来自DB,

我想一直看到所选的元素,尤其是在重新构建页面之后。

这就像;

<select id="select-firm" class="form-control" name="firmId" size="20">
</select>

我正在使用Ajax调用来检索元素。

我应该怎么做才能一直看到所选的元素?

感谢

有两个选项,这取决于您是想在本地为特定用户保存选择,还是想将选择存储在服务器上。

你可以使用

本地存储

cookie

以本地保存所选选项,并在下次刷新时检查是否保存了某些内容。

或者将所选内容返回到服务器以进行保存,下次刷新页面时,服务器应向您提供选项列表和已选择的选项。

您可以在服务器上提供映射并打印所选条目。

<?php
$selected = 3;
$output = [];
foreach( $lists as $item ){
$output[] = '<option value="' . $item['id'] . '"' . ($item['id']==$selected?' selected="selected"':null) . '>' . $item['name'] . '</option>';
}
echo $output;