Javascript 将值加载到 Selectize.js

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25778739/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 21:51:45  来源:igfitidea点击:

Loading values into Selectize.js

javascriptjqueryjsonselectize.js

提问by Alex.Ritna

Problem

问题

I have a text input that I have selectized as tags which works fine for querying remote data, I can search and even create new items using it and that all works OK.

我有一个文本输入,我选择了它作为标签,它可以很好地查询远程数据,我可以使用它搜索甚至创建新项目,一切正常。

Using selectize:

使用选择:

var $select = $('.authorsearch').selectize({
    valueField: 'AuthorId',
    labelField: 'AuthorName',
    searchField: ['AuthorName'],
    maxOptions: 10,
    create: function (input, callback) {
        $.ajax({
            url: '/Author/AjaxCreate',
            data: { 'AuthorName': input },
            type: 'POST',
            dataType: 'json',
            success: function (response) {
                return callback(response);
            }
        });
    },
    render: {
        option: function (item, escape) {
            return '<div>' + escape(item.AuthorName) + '</div>';
        }
    },
    load: function (query, callback) {
        if (!query.length) return callback();
        $.ajax({
            url: '/Author/SearchAuthorsByName/' + query,
            type: 'POST',
            dataType: 'json',
            data: {
                maxresults: 10
            },
            error: function () {
                callback();
            },
            success: function (res) {
                callback(res);
            }
        });
    }
});

The text box:

文本框:

<input class="authorsearch" id="Authors" name="Authors" type="text" value="" />

Examples:

例子:

Authors working

作者工作

Then when I select one (in this case 'apple') it comes up in a badge as you'd expect, and the underlying value of the textbox is a comma separated list of the values of these items.

然后,当我选择一个(在本例中为“苹果”)时,它会如您所愿出现在徽章中,并且文本框的基础值是这些项目值的逗号分隔列表。

Author with badge

带徽章的作者

Current Output

电流输出

The problem is when I load a page and want values retrieved from the database to be displayed in the selectized text input as tags, it only loads the values and I can see no way of displaying the displayname instead.

问题是当我加载页面并希望从数据库中检索的值作为标签显示在选定的文本输入中时,它只加载值而我看不到显示显示名称的方法。

<input class="authorsearch" id="Authors" name="Authors" type="text" value="1,3,4" />

Numbers only

仅数字

Desired Ouput

期望输出

I have tried all sorts of values for the inputs value field to have it load the items as showing their displayname and not their values. Below is an example of a single object being returned as JSON, being able to load a JSON array of these as selectized tags would be ideal.

我已经尝试了输入值字段的各种值,让它加载项目以显示它们的显示名称而不是它们的值。以下是单个对象作为 JSON 返回的示例,能够加载这些对象的 JSON 数组作为选定标签将是理想的选择。

[{"AuthorId":1,"AuthorName":"Test Author"},
 {"AuthorId":3,"AuthorName":"Apple"},
 {"AuthorId":4,"AuthorName":"Test Author 2"}]

enter image description here

在此处输入图片说明

How can I go about this? Do I need to form the value of the text box a particular way, or do I need to load my existing values using some javascript?

我该怎么办?我是否需要以特定方式形成文本框的值,还是需要使用某些 javascript 加载现有值?

采纳答案by Alex.Ritna

I ended up using the onInitializecallback to load the JSON values stored in a data-*field. You can see it in action here in this jsfiddle.

我最终使用onInitialize回调来加载存储在data-*字段中的 JSON 值。你可以在这个 jsfiddle 中看到它的实际效果

<input class="authorsearch" id="Authors" name="Authors" type="text" value="" 
 data-selectize-value='[{"AuthorId":1,"AuthorName":"Test"},{"AuthorId":2,"AuthorName":"Test2"}]'/>

Basically it parses the data-selectize-valuevalue and then adds the option(s) to the selectize then adds the items themselves.

基本上它解析data-selectize-value值,然后将选项添加到 selectize 然后添加项目本身。

onInitialize: function() {
    var existingOptions = JSON.parse(this.$input.attr('data-selectize-value'));
    var self = this;
    if(Object.prototype.toString.call( existingOptions ) === "[object Array]") {
        existingOptions.forEach( function (existingOption) {
            self.addOption(existingOption);
            self.addItem(existingOption[self.settings.valueField]);
        });
    }
    else if (typeof existingOptions === 'object') {
        self.addOption(existingOptions);
        self.addItem(existingOptions[self.settings.valueField]);
    }
}

My solution does presume my JSON object is formed correctly, and that it's either a single object or an object Array, so it may or may not be appropriate for someone elses needs.

我的解决方案确实假定我的 JSON 对象形成正确,并且它是单个对象或对象数组,因此它可能适合也可能不适合其他人的需求。

So it parses:

所以它解析:

[{"AuthorId":1,"AuthorName":"Test"},
 {"AuthorId":2,"AuthorName":"Test2"}]

To:

到:

enter image description here

在此处输入图片说明

Based of course on my selectize settings in my original post above.

当然基于我在上面的原始帖子中的选择设置。

回答by Helios

Thanks to your answer and based on your onInitialize() approach I ended up with a similar solution. In my case I just needed to translate one value, thus I was able to store the id and label as data attributes in the input field.

感谢您的回答并基于您的 onInitialize() 方法,我最终得到了类似的解决方案。就我而言,我只需要翻译一个值,因此我能够将 id 和标签作为数据属性存储在输入字段中。

<input type="text" data-actual-value="1213" data-init-label="Label for 1213 item">

Then on initialization:

然后在初始化:

onInitialize: function() {
        var actualValue = this.$input.data('actual-value');
        if (actualValue){
            this.addOption({id: actualValue, value: this.$input.data('init-label')});
            this.setValue(actualValue);
            this.blur();
        }
    }

According to these options:

根据这些选项:

$('input').selectize({
    valueField: 'id',
    labelField: 'value',
    searchField: 'value',
    create: false,
    maxItems: 1,
    preload: true,
    // I had to initialize options in order to addOption to work properly 
    // although I'm loading the data remotely
    options: [],
    load: ... ,
    render: ...,
    onInitialize: ....
});

I know this does not answer your question but wanted to share just in case this could help someone.

我知道这不能回答您的问题,但想分享以防万一这可以帮助某人。

回答by chifliiiii

Even simpler on new version of selectize using items attribute. Basically to set a selected item you need to have it first in the options. But if you use remote data like me, the options are empty so you need to add it to both places.

使用 items 属性在新版本的 selectize 上更简单。基本上要设置选定的项目,您需要首先在选项中使用它。但是如果你像我一样使用远程数据,选项是空的,所以你需要把它添加到两个地方。

$('select').selectize({
        valueField: 'id',
        labelField: 'name',
        options:[{id:'123',name:'hello'}],
        items: ['123'],
        ...

This is working for me and took me a while to figure it out... so just sharing

这对我有用,我花了一段时间才弄明白……所以只是分享