duangengruan2144 2014-08-05 03:02
浏览 101
已采纳

select2添加带有确认框的新标签

In Select2 I have basic tagging functionality working. The tagging system is works in an insert project page, where I can tag projects with certain predefined tags that are stored in a database and called by AJAX, and also in an update project page where the same mechanism is at play with the addition of bringing up currently stored tags in the tag field.

I want it so that if no tag currently exists, the user will receive a confirmation box that asks whether or not they want to add a new tag, and by hitting ok that tag will then be stored in the database. There should also be a sort of buffer time of a few seconds for Select2 to catch up with looking up the tags otherwise it might create duplicates?

I have read something here that shows how to do the jquery part, albeit its incomplete for my purposes. Can anyone shed light into how I might do this? I am not looking for complete answers, but merely guidance.

  • 写回答

1条回答 默认 最新

  • doucong4535 2014-08-05 15:10
    关注

    Have a look at this question: How do I fire a new ajax on select2 new /remove tag event?

    In your case, using your fiddle, you can use something like:

    $('#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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥15 键盘指令混乱情况下的启动盘系统重装