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.

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

报告相同问题?