简体   繁体   English

jQuery select2动态选项

[英]jQuery select2 dynamic options

I have a multiselect that I want to use as a search box so that the user can search by category, event type, location and keywords. 我有一个多选项,我想用作搜索框,以便用户可以按类别,事件类型,位置和关键字进行搜索。 It has the following structure: 它具有以下结构:

<select name="search-term[]" multiple="multiple">
    <optgroup label="Categories">
        <option value="category_4">Internal</option>
        <option value="category_2">Business</option>
        <option value="category_5">External</option>
        <option value="category_1">Science</option>
        <option value="category_6">Sports and Social</option>
    </optgroup>
    <optgroup label="Event Types">
        <option value="eventtype_2">Meeting</option>
        <option value="eventtype_3">Social Activity</option>
        <option value="eventtype_4">Sporting Activity</option>
        <option value="eventtype_1">Symposium</option>
    </optgroup>
    <optgroup label="Locations">
        <option value="location_2">Office 1</option>
        <option value="location_3">Office 2</option>
        <option value="location_1">Office 3</option>
    </optgroup>
</select>

I have initialised select2 with the tags option set to true so like so: 我初始化了select2,并将tags选项设置为true,如下所示:

$('select').select2({
    tags : true,
    createTag: function (params)
    {
        return {
            id: 'keyword_' + params.term,
            text: params.term,
            newOption: true
        }
    }
});

This allows users to enter a new option if it doesn't exist and takes care of the keywords requirement. 这样,用户可以输入一个不存在的新选项,并且可以满足关键字要求。 Any new tags are appended with keyword_ so that the server knows how to handle them when the form is submitted. 任何新标记都附加有keyword_以便服务器在提交表单时知道如何处理它们。

This is all working as I expected however the issue I've come across is if someone wants to search for a keyword that is called the same as one of the other options then they aren't able to create a new keyword tag it will only let them select the existing option. 这一切都按照我的预期工作但是我遇到的问题是,如果有人想要搜索与其他选项之一相同的关键字,那么他们将无法创建新的关键字标签让他们选择现有的选项。 For example if I search Office 1 I may want to search for events that are located at office 1 or I may want to do a keyword search so that I am searching for events that have office 1 in the title. 例如,如果我搜索Office 1我可能想要搜索位于办公室1的事件,或者我可能想要进行关键字搜索,以便我搜索标题中包含office 1的事件。 The problem is currently I'm only able to select the location option I'm not able to create a new tag. 问题是当前我只能选择位置选项,但无法创建新标签。 Does anyone know how I could achieve this? 有谁知道我怎么能做到这一点?

I achieved this in the end by using an AJAX datasource which gives you much more control over what options are shown to the user. 我最终通过使用AJAX数据源实现了这一点,这使您可以更好地控制向用户显示的选项。 Here is my code: 这是我的代码:

$('select').select2({
    ajax: {
        url: "/server.php",
        dataType: 'json',
        type: "GET",
        delay: 0,
        data: function (params) {
            var queryParameters = {
                term: params.term
            }
            return queryParameters;
        },
        processResults: function (data) {
            return {
                results: $.map(data, function (item) {
                    return {
                        text: item.text,
                        id: item.id,
                        children: item.children
                    }
                })
            };
        },
        cache: false
    },
    templateSelection: function(item)
    {
        return item.parent+': '+item.text;
    }
});

Contents of server.php: server.php的内容:

<?php
$term = !isset($_GET['term']) ? null : ucfirst($_GET['term']);

$categories = array('Meeting', 'Seminar', 'Sports and Social');
$locations = array('Cambridge', 'London', 'Northwich');
$matching_categories = array();
$matching_locations = array();

foreach($categories as $i => $cat) {
    if(is_null($term) || stripos($cat, $term)!==false) {
        $matching_categories[] = array(
            'id' => 'category_'.$i,
            'text' => $cat,
            'parent' => 'Category'
        );
    }
}

foreach($locations as $i => $loc) {
    if(is_null($term) || stripos($loc, $term)!==false) {
        $matching_locations[] = array(
            'id' => 'location_'.$i,
            'text' => $loc,
            'parent' => 'Location'
        );
    }
}

$options = array();

if(!empty($matching_categories)) {
    $options[] = array(
        'text' => 'Category',
        'children' => $matching_categories
    );
}

if(!empty($matching_locations)) {
    $options[] = array(
        'text' => 'Location',
        'children' => $matching_locations
    );
}

if(!is_null($term)) {
    $options[] = array(
        'text' => 'Keyword',
        'children' => array(
            array(
                'id' => 'keyword_'.$term,
                'text' => $term,
                'parent' => 'Keyword'
            )
        )
    );
}

echo json_encode($options);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM