在Laravel中使用AJAX填充Selectopt optgroup列

时间:2018-07-31 11:07:37

标签: javascript jquery ajax laravel selectize.js

我正在尝试使用Selectize在客户端将属性分配给产品。 在Laravel中,针对Ajax的请求,我从Controller返回一个JSON对象,如下所示:

    $attribs = AttributeClass::find($request->id)->attributes;

    $attributes = array();
    foreach($attribs as $attrib){
        $options = array();
        foreach($attrib->options as $opt){
            $options[] = array(
                'id' => $opt->id,
                'name' => $opt->name
            );
        }
        $attributes[] = array(
            'id' => $attrib->id,
            'name' => $attrib->name,
            'options' => $options
        );
    }

    return response()->json([
        'attributes' => $attributes
    ]);

JSON输出看起来像这样:

"{"attributes":[
    {"id":15,
    "name":"Color",
    "options":[
            {"id":63,"name":"Red"},
            {"id":64,"name":"Black"},
            {"id":65,"name":"White"},
    ]},
    {"id":16,
    "name":"Material",
    "options":[
            {"id":69,"name":"Leather"},
            {"id":70,"name":"Rubber"},
            {"id":71,"name":"Suede"},
    ]},
    {"id":17,
    "name":"Size",
    "options":[
            {"id":73,"name":"40"},
            {"id":74,"name":"41"},
            {"id":75,"name":"42"},
            {"id":76,"name":"43"},
            {"id":77,"name":"44"}
    ]}
]}"

在DOM中,我有一个div容器,其ID为#attributesContainer。我正在select内创建一个新的div元素,并尝试populate and selectize在如下所示的ajax响应中提到select

    $('#attributesContainer').empty().append(
          '<label class="col-md-3 control-label">Attributes</label>'+
          '<div class="col-md-9">'+
          '<select id="inputAttributes" name="inputAttributes" multiple></select>'+
          '<span class="help-block">Choose product attributes</span>'+
          '</div>'
     );

     var optGroups = [];
     var options = [];

     $.each(data.attributes, function(index, attribute) {
            var newElement = {};
            newElement['id'] = attribute.id;
            newElement['name'] = attribute.name;
            optGroups.push(newElement);

            $.each(attribute.options, function(index, option){
                var newElement = {};
                newElement['id'] = option.id;
                newElement['attribute'] = attribute.name;
                newElement['name'] = option.name;
                options.push(newElement);
            });                        
    });

    $('#inputAttributes').selectize({
            options: options,
            optgroups: optGroups,
            labelField: 'name',
            valueField: 'id',
            optgroupField: 'attribute',
            optgroupLabelField: 'name',
            optgroupValueField: 'id',
            searchField: ['name'],
            plugins: ['optgroup_columns', 'remove_button']
    });

预期的行为是多个列,例如Selectize文档中的以下示例: enter image description here

但是我将所有值都放在一列下,如下所示: enter image description here

我在这里想念什么或做错了什么?请指导。

PS:我还想限制用户从每一列中只选择一个值。 API是否支持?有什么功能可以做到这一点吗?如何在Selectize.js中实现此行为?

1 个答案:

答案 0 :(得分:0)

出于某种原因,向selectize提供optgroup和选项对我不起作用。通过首先在DOM中创建select元素并通过所有optgroup和选项填充它来解决此问题。

我通过替换来做到这一点

var optGroups = [];
 var options = [];

 $.each(data.attributes, function(index, attribute) {
        var newElement = {};
        newElement['id'] = attribute.id;
        newElement['name'] = attribute.name;
        optGroups.push(newElement);

        $.each(attribute.options, function(index, option){
            var newElement = {};
            newElement['id'] = option.id;
            newElement['attribute'] = attribute.name;
            newElement['name'] = option.name;
            options.push(newElement);
        });                        
});

$('#inputAttributes').selectize({
        options: options,
        optgroups: optGroups,
        labelField: 'name',
        valueField: 'id',
        optgroupField: 'attribute',
        optgroupLabelField: 'name',
        optgroupValueField: 'id',
        searchField: ['name'],
        plugins: ['optgroup_columns', 'remove_button']
});

具有:

    $.each(data.attributes, function(i, optgroups) {
        $.each(optgroups, function(groupName, options) {
                var $optgroup = $("<optgroup>", {
                    label: groupName
                });
                $optgroup.appendTo('#inputAttributes');
                $.each(options, function(j, option) {
                    var $option = $("<option>", {
                        text: option.name,
                         value: option.id
                    });
                    $option.appendTo($optgroup);
                });
            });
     });

    $('#inputAttributes').selectize({
        sortField: 'text',
        plugins: ['optgroup_columns', 'remove_button']
    });

仍然在寻找我的第二个问题,即如何限制用户从每个optgroup列中仅选择一个选项?

编辑: 我已经从每个optgroup这样实现了单个选项的选择,此代码还显示了带有选定选项的optgroup名称,例如Size > SmallColor > Black,希望对您有所帮助。这是完整的代码:

                var vals = {};

                $.each(data.attributes, function(i, optgroups) {
                    $.each(optgroups, function(groupName, options) {
                        var $optgroup = $("<optgroup>", {
                            label: groupName
                        });
                        $optgroup.appendTo('#inputAttributes');
                        $.each(options, function(j, option) {
                            var $option = $("<option>", {
                                text: option.name,
                                value: option.id,
                            });
                            vals[option.id] = groupName;
                            $option.appendTo($optgroup);
                        });
                    });
                });

                var $select = $('#inputAttributes').selectize({
                    sortField: 'text',
                    placeholder: 'Select attributes...',
                    lockOptgroupOrder: true,
                    plugins: ['optgroup_columns', 'remove_button']
                });

                var selectize = $select[0].selectize;

                var selections = [];

                selectize.on('item_add', function(value, $item){
                    var group = vals[value];

                    var v_text = $item.text();
                    v_text = v_text.substring(v_text.indexOf(">") + 1);
                    v_text = group+' > '+v_text.substring(0, v_text.length-1);

                    $item.html(v_text+
                        '<a href="javascript:void(0)" class="remove" tabindex="-1" title="Remove">×</a>'
                        );

                    // $item.text(group+' > '+$item.text());


                    if(selections.find(x => x.group === group)){
                        var v_index = selections.findIndex(x => x.group === group);
                        var v = selections[v_index].value;

                        selectize.removeItem(v, silent = true);
                    }

                    var newSelection = {};
                    newSelection['group'] = group;
                    newSelection['value'] = value;

                    selections.push(newSelection);
                });

                selectize.on('item_remove', function(value, $item){
                    var v_index = selections.findIndex(x => x.value === value);
                    selections.splice(v_index, 1);
                });

PS::请指导是否存在更好的解决方案。