我在一个选择框中使用了
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>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。