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

前端之家收集整理的这篇文章主要介绍了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,并在选择框中填充并选择.

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

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

@H_301_12@<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>
原文链接:https://www.f2er.com/jquery/179273.html

猜你在找的jQuery相关文章