简体   繁体   English

Select2,追加不显示标题

[英]Select2, append doesn't show the title

so I had this problem with select2 autocomplete box, when I'm trying to create the object to the box, it is creating fine, but the name of the object isn't showing in the box and the only thing is showing is "X" to clear the object. 所以我在选择2自动完成框时遇到了这个问题,当我尝试向该框创建对象时,它创建得很好,但是该对象的名称未显示在框中,唯一显示的是“ X以清除对象。

The main focus of the box is to set the values from the database to edit(add, remove etc.) it later. 该框的主要焦点是设置数据库中的值,以便以后对其进行编辑(添加,删除等)。 The way I want to do it is first get object from database and then create it in the select2 box. 我要执行的方法是先从数据库中获取对象,然后在select2框中创建它。

Here's my javascript file: 这是我的JavaScript文件:

$('#recipefield').select2({
        id: function(data){return data.id;},
        maximumSelectionLength: 5,
        minimumSelectionLength: 3,
        ajax: {
            url: function () {
                return getTypedAutoCompleteUrl();
            },
            dataType: 'json',
            processResults: function (data) {
                  return {
                    results: data
                  };
                }
        },
        templateResult: formatState,
        templateSelection: formatState
    });
});

function getTypedAutoCompleteUrl() {
    return '/api/v1/recipe/' + $('#menutype').val();
}

function formatState (state) {
    if (!state.id) {
        return state.text;
    }
    return state.title;
}

And that's what I'm using to add object to the box: 这就是我用来将对象添加到框中的内容:

var data = {
    id: 1,
    text: 'text'
};
var newOption = new Option(data.text, data.id, true, true);
$('#recipefield').append(newOption).trigger('change');

So the box looks like this after adding object to it: 因此,在向其添加对象后,该框如下所示:
向其添加对象

And here is what it looks like when I select object manually: 这是我手动选择对象时的样子:
手动选择对象

So, finally I did make it work, maybe it will be useful for someone. 所以,最后我确实做到了,也许对某人有用。

Created this function. 创建了此功能。

function recipeHelper(){
    var recipeList = $("#recipefield").select2("data");
    for(i=0; i<recipeList.length; i++){
        var recipeObject = recipeList[i];
        recipeObject.name = recipeObject.text;
    }
    $("#recipefield").trigger('change');
}

The "recipeHelper" function is called in the “ recipeHelper”函数在

$(document).ready(function() {
    ...
    recipeHelper();
});

Hope it will help somebody. 希望它能帮助到别人。

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

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