我使用 selectize.js 作为标签。我想在我的选择上动态添加新标签。当我在 onItemAdd 事件中使用 ajax 请求将新项目添加到我的数据库时,此选项没有正确的值。 ajax完成后如何更改项目的值?
我的代码:
$('.campaign-tag-selectize').selectize({
plugins : ['remove_button', 'restore_on_backspace'],
create : true,
onItemAdd : function (value, $item) {
if(!Number.isInteger(value)){
$.post('/ajaxrequesturl', {'title':value, "_token": $('input[name="_token"]').val()}, function (returnVal) {
// I try to change value with change attr but not working :)
$item.attr('data-value', returnVal.id);
console.log(returnVal);
});
}
}
});
使用 onOptionAdd 来代替!
// Apply Selectize to the your dropdown
$('.campaign-tag-selectize').selectize({
plugins : ['remove_button', 'restore_on_backspace'],
create : true,
onOptionAdd: function (value, data) {
var selectize = this;
// Added itmes gets same value as text
if (data.value === value) {
// If the newly added option's value is not what you want, modify it.
if(!Number.isInteger(data.value)) {
selectize.removeOption(value); // Remove the newly added option
selectize.addOption({ value: '0', text: data.text }); // Re Add it with wanted value '0' in this case
selectize.setValue('0'); // Set the new value
}
}
}
});