在selctize.js中的选定值中显示optgroup

时间:2017-01-20 11:07:27

标签: selectize.js

我们有一个选择字段,可以选择多个值。这些值按optgroups分组。为了便于理解,某些值可以在多个optgroup中,我们也希望在所选字段的标签中看到optgroup的名称。我们怎样才能做到这一点?

如果您选择“First Item”,您将不知道选择了哪一个,Store或Warehouse,请参阅以下小提琴。

谢谢!

https://jsfiddle.net/4t8fjj7g/1/

HTML:

<select name="test" id="test-select" multiple="multiple">
  <optgroup label="Store">
    <option data-type="stores" value="1">First item</option>
    <option data-type="stores" value="2">Second item</option>
  </optgroup>
  <optgroup label="Warehouse">
    <option data-type="warehouses" value="3">First item</option>
    <option data-type="warehouses" value="4">Second item</option>
  </optgroup>
</select>

这是javascript代码:

$('select#test-select').selectize({
  searchField: ['text', 'type']
});

2 个答案:

答案 0 :(得分:0)

基本上,Daffy建议的是,但...... 您可以对下拉选项和所选项目使用自定义渲染功能:

$('select#test-select').selectize({
  searchField: ['text', 'type'],
  render: {
    item: itemRenderFunction,
    option: optionRenderFunction
  }
});

这样可以避免选定项目列表中的标签乘法。

答案 1 :(得分:0)

我所做的是让值具有optgroup,然后具有optgroup_value之类的值,然后当表单在服务器上提交或在JS中执行某些操作时,我可以通过分解字符串来获取它:

<select multiple class="my-select">
    <optgroup label="taxes">
        <?php foreach ( $taxes as $tax) : ?>
            <option value="tax_<?php echo $tax->slug; ?>"><?php echo $tax->name; ?></option>
        <?php endforeach; ?>
    </optgroup>
    <optgroup label="Version">
        <?php foreach ( $my_versions as $version ) : ?>
            <option value="version_<?php echo $version->slug; ?>"><?php echo $version->name; ?></option>
        <?php endforeach; ?>
    </optgroup>
    <optgroup label="Language">
        <?php foreach ( $my_languages as $language ) : ?>
            <option value="language_<?php echo $language->slug; ?>"><?php echo $language->name; ?></option>
        <?php endforeach; ?>
    </optgroup>
</select>

然后

<?php
foreach ( $_POST['taxes'] as $val ) {
    if ( ! empty( $val ) ) {
        // $val_parts is an array with
        // $val_parts[0] = optgroup only
        // $val_parts[1] = the value of the option minus optgroup
        $val_parts = explode( "_", $val );

        // My use case to add a meta_query to a WP_Query so add filter based on both values
        $meta_arg = array(
            'taxonomy' => "my_" . $val_parts[0], // custom prefix then optgroup
            'field'    => 'slug',
            'terms'    => $val_parts[1] // value
        );

        // Add to running array and possibly do again
        array_push( $args['tax_query'], $meta_arg );
    }
}