如果Selectize.js选择框中尚不存在,则创建一个项目,然后用ajax更新新添加的项目 [英] Creating an item if not already exists in Selectize.js select box and ajax update the new added item

查看:157
本文介绍了如果Selectize.js选择框中尚不存在,则创建一个项目,然后用ajax更新新添加的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在选择框中使用了 Selectize.js .选项列表,我需要添加一个新项目.添加新项目后,我想进行一次ajax调用以将新添加的项目更新到我的数据库中.

I was using Selectize.js in a select box, What i need is, if an item is not in the list of options i would need to add a new item. When new item is added, i want to have an ajax call to update the newly added item to my database.

在他们的文档中,它说我们可以使用创建"选择添加项.

In their documentiation, it says that we can use "create" to have the selectize to add an item.

create-允许用户创建不在选项列表中的新项目.此选项可以是以下任意值:"true"(默认行为),"false"(禁用)或接受两个参数的函数:"input"和"callback".应该使用该选项的最终数据来调用回调.

create - Allows the user to create a new items that aren't in the list of options. This option can be any of the following: "true" (default behavior), "false" (disabled), or a function that accepts two arguments: "input" and "callback". The callback should be invoked with the final data for the option.

但是我不明白如何在这里使用回电.有人可以帮忙吗?

But i am not able to understand how to use the call back here. can anyone help?

以下是我的内容的示例,值是db中各项的id.我想将新项目添加到db中,并从db中返回id作为ID的值,然后填充并在选择框中选择它.

The following is an example of my content, the values are ids of the items in the db. I would like to have the new item added to db and returned with the value as id from db and populate and get selected in the select box.

<select name="fruits" id="fruits" placeholder="Select a fruit" >
    <option value="1">Apple</option>
    <option value="2">Orange</option>
    <option value="3">Mango</option>
    <option value="4">Grape</option>
</select>

<script>
    $(function(){
        $('#fruits').selectize({
            create:function (input, callback){

           }
        });
    });
</script>

推荐答案

实际上,您必须返回一个对象,该对象的属性与labelField和valueField选项的名称匹配:

Actually you must return an object with properties that match the names for your labelField and valueField options:

<script>
    $(function(){
        $('#fruits').selectize({
            create:function (input){
               return { value:123, text:input};
           }
        });
    });
</script>

如果您需要执行远程操作,则可以这样进行编码:

If you needed to perform a remote operation you would code it like this:

<script>
    $(function(){
        $('#fruits').selectize({
            create:function (input, callback){
                $.ajax({
                    url: '/remote-url/',
                    type: 'GET',
                    success: function (result) {
                        if (result) {
                            callback({ value: result.id, text: input });
                        }
                    }
                });
            }
        });
    });
</script>

这篇关于如果Selectize.js选择框中尚不存在,则创建一个项目,然后用ajax更新新添加的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆