使用 Bootstrap Dual Listbox 插件时,您可能希望在页面加载时就显示一些已选数据。这可以通过从后端加载数据并在初始化插件时将数据设置为已选择状态来实现。

以下是一个示例代码,演示如何从后端加载数据并将其设置为 Bootstrap Dual Listbox 的已选数据:

$('.dual_select').bootstrapDualListbox({
    nonSelectedListLabel: '可选密钥模板',
    selectedListLabel: '已选密钥模板',
    preserveSelectionOnMove: 'moved',
    moveOnSelect: false,           // 出现一个剪头,表示可以一次选择一个
    filterTextClear: '展示所有',
    moveSelectedLabel: '添加',
    moveAllLabel: '添加所有',
    removeSelectedLabel: '移除',
    removeAllLabel: '移除所有',
    infoText: '共{0}个',
    showFilterInputs: false,       // 是否带搜索
    selectorMinimalHeight: 160
});

$.ajax({
    url: 'your_backend_url',
    method: 'GET',
    success: function(response) {
        // 假设response是从后端获取的已选择数据数组
        var selectedData = response.map(function(item) {
            return {
                value: item.id,
                text: item.name
            };
        });
        
        // 将已选择的数据传递给bootstrapDualListbox的selected属性
        $('.dual_select').bootstrapDualListbox('refresh', true);
        $('.dual_select').bootstrapDualListbox('selected', selectedData);
    },
    error: function(error) {
        console.log(error);
    }
});

在这个例子中,首先使用 ajax 请求从后端获取已选择数据。然后使用 map 方法将每个元素转换为 Bootstrap Dual Listbox 所需的格式,即包含 valuetext 属性的对象。最后,使用 selected 方法将已选择的数据传递给插件。

请注意,上述代码中的 'your_backend_url' 应该替换为实际的后端接口地址。

Bootstrap Dual Listbox:加载预选数据

原文地址: https://www.cveoy.top/t/topic/pE1x 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录