php - 选择2 添加带有确认框的新标签

标签 php jquery ajax json jquery-select2

Select2中,我可以使用基本的标记功能。标记系统在插入项目页面中工作,我可以在其中使用存储在数据库中并由 AJAX 调用的某些预定义标记来标记项目,并且也在更新项目页面中工作,其中相同的机制通过添加在标签字段中显示当前存储的标签。

我希望这样,如果当前不存在标签,用户将收到一个确认框,询问是否要添加新标签,然后单击“确定”,该标签将存储在数据库中。还应该有一种几秒钟的缓冲时间,让 Select2 能够跟上查找标签的速度,否则可能会创建重复项?

我读过一些东西here这展示了如何执行 jquery 部分,尽管它对于我的目的来说并不完整。任何人都可以阐明我如何做到这一点吗?我并不是在寻找完整的答案,而只是寻求指导。

最佳答案

看看这个问题:How do I fire a new ajax on select2 new /remove tag event?

在你的情况下,使用你的 fiddle ,你可以使用类似的东西:

$('#tags').on("change", function(e){
    if (e.added) {
        if (/ \(new\)$/.test(e.added.text)) {
           // A new tag was added
           // Prompt the user
           var response = confirm("Do you want to add the new tag "+e.added.id+"?");

           if (response == true) {
              // User clicked OK
              console.log("Sending the tag to the server");
              $.ajax({
                   type: "POST",
                   url: '/someurl&action=addTag',
                   data: {id: e.added.id, action: add},    
                   error: function () {
                      alert("error");
                   }
               });
           } else {
                // User clicked Cancel
                console.log("Removing the tag");
                var selectedTags = $("#tags").select2("val");
                var index = selectedTags.indexOf(e.added.id);
                selectedTags.splice(index,1);
                if (selectedTags.length == 0) {
                    $("#tags").select2("val","");
                } else {
                    $("#tags").select2("val",selectedTags);
                }
           }
        }
    }
});

Draft fiddle here .

关于php - 选择2 添加带有确认框的新标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25130537/

相关文章:

php - 如何在 php 生成的 zip 中排除文件

javascript - 如何从用户填写的文本字段中获取 url,并使用 html 或 javascript 在新选项卡中查看

javascript - jquery 不继续执行其余的 javascript 代码

javascript - 使用javascript在tinymce编辑器中更改文本框文本

javascript - 如何仅使用 jQuery 构建类似 Quicksand 的动画

javascript - 如何获得文字中的金额?

php - onclick ="$.post(this.href); return false;"无法正常工作

java - 如何确定安全链接的下载链接?

javascript - 语法错误 : invalid regular expression flag ajax,

javascript - Rails j 局部渲染