Selectpicker - 所选选项未显示在按钮中

Posted

技术标签:

【中文标题】Selectpicker - 所选选项未显示在按钮中【英文标题】:Selectpicker - selected option is not shown in the button 【发布时间】:2021-07-25 05:35:15 【问题描述】:

我在当前的 Web 项目中使用 Selectpicker 插件。我也在使用 Codeigniter 4 作为 Web 框架。

情况说明: 我首先从数据库中加载选择字段的选择选项。然后通过单击按钮执行 Ajax 请求。生成的 json 响应包含要为选择选项选择的值。

问题: The select options are selected appropriately according to the value in the json response (there is a tick next to the options), but they are not displayed in the button, so the title of the button is not updated.

示例: 对于字段“staff_number”,选项“1234”和“5678”从数据库中加载。单击按钮后,将执行 Ajax 请求,字段“staff_number”的结果为“1234”。然后在选择字段中选择此选项。因此,当您单击它时,该选项旁边会出现一个勾号(见图1)。此选项出现,但不在按钮标题中,因为它仍然显示“请选择”(见图 2)。

图一: select option

图二: empty button title

我当前的视图代码如下所示:

<label for="staff_number">Staff number:*</label><br>
<select class="selectpicker" id="staff_number" multiple name="staff_number[]" title="Please select">
<?php foreach($staff_numbers as $each):?>
<option value="<?=$each?>" <?php echo set_select('staff_number',$each, ( !empty($data) && $data == $each ? TRUE : FALSE )); ?>> <?=$each?></option>
<?php endforeach;?>
</select>   

我当前的 Ajax 调用如下所示:

$.ajax(
url: 'getInformation.php',
type: 'POST',
data: field : 'id', value: id.substring(4),
success: function(data) 
//JSON needs to be parsed to be accessible in JS
var json = JSON.parse(data);
                            
//Asign values to input fields
var staff_number= json['staff_number'];
$.each(staff_number.split(","), function(i,e)
$("#staff_number option[value='" + e + "']").prop("selected", true);                            
);
//$('.selectpicker').selectpicker('render');
//$('.selectpicker').selectpicker('refresh');

); 

如果有任何建议,我将不胜感激。 :)

最好的问候 施瓦拉克

【问题讨论】:

【参考方案1】:

您首先需要取消选择所有选择的选项,并且您需要在选择后刷新选择器,如下所示:

$.ajax(
url: 'getInformation.php',
type: 'POST',
data: field : 'id', value: id.substring(4),
success: function(data) 
//JSON needs to be parsed to be accessible in JS
var json = JSON.parse(data);
                            
//deselect all option first
 $("#staff_number option:selected").removeAttr("selected");

//Asign values to input fields
var staff_number= json['staff_number'];
$.each(staff_number.split(","), function(i,e)
    $("#staff_number option[value='" + e + "']").prop("selected", true);                            
);
//$('.selectpicker').selectpicker('render');
$('.selectpicker').selectpicker('refresh');

);

【讨论】:

感谢您的方法。但是,问题仍然存在。注意:我再次调整了我的帖子(添加了两张图片)。

以上是关于Selectpicker - 所选选项未显示在按钮中的主要内容,如果未能解决你的问题,请参考以下文章

Selectpicker 选择了第一个选项,但 selectpicker 标题是“未选择”

显示所选选项的按钮

在 Bootstrap 选择器上使用 jQuery 取消选择选项

想从下拉列表中选择选项并根据所选选项更改按钮的标题...如何?

选择其他按钮时,ListView 突出显示所选项目颜色不会保持不变

ReactJS Reactstrap 输入下拉菜单未显示所选值