gpt4 book ai didi

jquery - 创建一个项目(如果 Selectize.js 选择框中尚不存在)并使用 ajax 更新新添加的项目

转载 作者:行者123 更新时间:2023-12-03 21:54:39 24 4
gpt4 key购买 nike

我正在使用Selectize.js在选择框中,我需要的是,如果某个项目不在选项列表中,我需要添加一个新项目。添加新项目时,我希望进行 ajax 调用以将新添加的项目更新到我的数据库。

在他们的documentiation中,它说我们可以使用“create”来选择添加项目。

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 { value:123, text:input};
}
});
});
</script>

如果您需要执行远程操作,您可以像这样编写代码:

<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>

关于jquery - 创建一个项目(如果 Selectize.js 选择框中尚不存在)并使用 ajax 更新新添加的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24366365/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com