未找到结果时向远程数据添加新记录 - select2

时间:2017-07-09 07:59:36

标签: jquery-select2

我有一个文本框,我使用select2库。

HTML

<div class="form-group">
    <label for="tags" class="control-label">Tags</label>
    <select class="tagsSearch" class="form-control" ng-model="post.tags" id="tags" style="width: 100%">
    </select>
</div>

JS:

$(".tagsSearch").select2({
placeholder: 'Search for tags',
delay: 250,
tags: true,
multiple: true,
tokenSeparators: [',', ' '],
minimumInputLength: 2,
minimumResultsForSearch: 1,
ajax: {
    url: function (params) {
        return '/api/searchTags';
    },
    dataType: "json",
    type: "GET",
    data: function (params) {
        return {
            text: params.term 
        };
    },
    processResults: function(data){
        return{
            results: $.map(data, function(obj){
            return {
                id: obj.name, text: obj.name
            };
          })
        };
    }}
});

这非常有效,因为我触发了 / api / searchTags API来查找要自动填充的新字段。如果未找到匹配项,则用户可以选择创建新匹配项。

我希望能够通过API将这个新选择的文本添加到远程数据源,例如:

/ API / addToTags

但是,我是否会触发该事件?

或者,我也可以“标记”这些不匹配的字段,以便在提交表单时,我可以查找这些标记的字段并使用该字段创建API。

我希望这很清楚。任何意见都将不胜感激。

1 个答案:

答案 0 :(得分:1)

您可以在输入中获取所有标记&#39;更改&#39;事件,您可以在服务器上检查哪个标签已存在

$(".tagsSearch").select2({
    placeholder: 'Search for tags',
    delay: 250,
    tags: true,
    multiple: true,
    tokenSeparators: [',', ' '],
    minimumInputLength: 2,
    minimumResultsForSearch: 1,
    ajax: {
         url: function (params) {
            return '/api/searchTags';
         },
         dataType: "json",
         type: "GET",
         data: function (params) {
            return {
                text: params.term 
         };
    },
    processResults: function(data){
        return{
            results: $.map(data, function(obj){
            return {
                id: obj.name, text: obj.name
            };
          })
        };
    }}
})
.on('change', function(e){
    // $(this).val() - array of tags in input
    $.ajax({
            type: "POST",
            dataType: 'json',
            url: '/api/addToTags',
            data: {
                tags: JSON.stringify($(this).val())
            },
            success: function (json) {
                 console.log(json);
            }
        });
});

或者 不允许用户通过方法cteateTag创建以数字开头的标签。然后改变&#39;您将能够分隔新标签和现有标签。如果你得到一个数字,这将意味着你得到了存在标签的id

$(".tagsSearch").select2({
    placeholder: 'Search for tags',
    delay: 250,
    tags: true,
    multiple: true,
    tokenSeparators: [',', ' '],
    minimumInputLength: 2,
    minimumResultsForSearch: 1,
    ajax: {
         url: function (params) {
            return '/api/searchTags';
         },
         dataType: "json",
         type: "GET",
         data: function (params) {
            return {
                text: params.term 
         };
    },
    // do not allow user to create tag with a number
    createTag: function (params) {
        if (/^\d+$/.test(params.term)) {
            return null;
        }
        return {id: params.term, text: params.term, newTag: true};
    }
    processResults: function(data){
        return{
            results: $.map(data, function(obj){
            return {
                id: obj.name, text: obj.name
            };
          })
        };
    }}
})
.on('change', function(e){
    // $(this).val() - array of tags in input

    var allTags = $(this).val();
    var newTags = [];
    allTags.forEach(function (el) {
        if (!parseInt(el)){ // if it is not NaN it is a new tag, in the other case this will be id of exist tag
            newTags.push(el);
        }
    });
    $.ajax({
            type: "POST",
            dataType: 'json',
            url: '/api/addToTags',
            data: {
                tags: JSON.stringify(newTags)
            },
            success: function (json) {
                 console.log(json);
            }
        });
});
相关问题