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.

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

报告相同问题?

悬赏问题

  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助