jquery – 如果Selectize.js选择框中不存在,创建一个项目,并且ajax更新新增的项目

我在一个选择框中使用了 Selectize.js,我需要的是,如果一个项目不在选项列表中,我需要添加一个新项目.当添加新项目时,我想要一个ajax调用来将新添加的项目更新到我的数据库.

在他们的documentiation中,它说我们可以使用“创建”来选择添加一个项目.

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.

但是我无法理解如何在这里使用回调.有人可以帮忙吗?

以下是我的内容的示例,值是数据库中项目的ID.我想要将新项目添加到数据库,并返回值为数据库中的id,并在选择框中填充并选择.

<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选项的名称相匹配:
<script>
    $(function(){
        $('#fruits').selectize({
            create:function (input){
               return { id:123,text:input};
           }
        });
    });
</script>

如果你需要执行一个远程操作,你可以这样编码:

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

相关文章

1.第一步 设置响应头 header(&#39;Access-Control-Allow...
$.inArray()方法介绍 $.inArray()函数用于在数组中搜索指定的...
jquery.serializejson.min.js的妙用 关于这个jquery.seriali...
JS 将form表单数据快速转化为object对象(json对象) jaymou...
jQuery插件之jquery.spinner数字智能增减插件 参考地址:http...