jQuery select2:重新创建重复标记

时间:2016-02-05 19:01:26

标签: javascript jquery ajax jquery-select2

我今天早些时候提出了一个问题(jquery select2: error in getting data from php-mysql)。但是,我正在尝试修复它并且现在这样做我有点奇怪的问题。我不确定为什么会这样。

以下是JavaScript代码。

<div class="form-group">
   <label class="col-sm-4 control-label">Product Name</label>
   <div class="col-sm-6">       
      <input type="hidden" id="tags" style="width: 300px"/>
   </div>
</div>

<script type="text/javascript">
var lastResults = [];

$("#tags").select2({
    multiple: true,
    placeholder: "Please enter tags",
    tokenSeparators: [","],
    initSelection : function (element, callback) {
        var data = [];
        $(element.val().split(",")).each(function () {
            data.push({id: this, text: this});
        });
        callback(data);
    },
    ajax: {
        multiple: true,
        url: "fetch.php",
        dataType: "json",
        type: "POST",
      data: function(term) {
                        return {q: term};
                    },
                    results: function(data) {
                        return {results: data};
                    }, 

    },
    createSearchChoice: function (term) {
        var text = term + (lastResults.some(function(r) { return r.text == term }) ? "" : " (new)");
        return { id: term, text: text };
    },
});

$('#tags').on("change", function(e){
    if (e.added) {
        if (/ \(new\)$/.test(e.added.text)) {
           var response = confirm("Do you want to add the new tag "+e.added.id+"?");
           if (response == true) {
              alert("Will now send new tag to server: " + e.added.id);
              /*
               $.ajax({
                   type: "POST",
                   url: '/someurl&action=addTag',
                   data: {id: e.added.id, action: add},    
                   error: function () {
                      alert("error");
                   }
                });
               */
           } else {
                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);
                }
           }
        }
    }
});
</script>

这是php代码( fetch.php

<?php 
// connect to database 
require('db.php');

// strip tags may not be the best method for your project to apply extra layer of security but fits needs for this tutorial 
$search = strip_tags(trim($_GET['q'])); 
//$search='te';
// Do Prepared Query 
$query = $mysqli->prepare("SELECT tid,tag FROM tag WHERE tag LIKE :search LIMIT 4");

// Add a wildcard search to the search variable
$query->execute(array(':search'=>"%".$search."%"));

// Do a quick fetchall on the results
$list = $query->fetchall(PDO::FETCH_ASSOC);

// Make sure we have a result
if(count($list) > 0){
   foreach ($list as $key => $value) {
    $data[] = array('id' => $value['tid'], 'text' => $value['tag']);                
   } 
} else {
   $data[] = array('id' => '0', 'text' => 'No Products Found');
}

// return the result in json
echo json_encode($data);

?>

select2版本为3.5

上面的代码可以使用fetch.php从数据库发送/接收请求。

问题出在我的数据库中有两个记录测试&amp; temp 当我标记其中任何一个时,它会创建新标记。

它应该是这样的:如果数据库有价值,那么它就不会创建具有相同名称的新标签。

enter image description here

更新

enter image description here

3 个答案:

答案 0 :(得分:2)

标签需要id和文本。您遇到的问题是您的文字与ID不匹配。

因此,即使你写了相同的文字,Select2认为新文本是一个新选项,因为id不匹配。

要解决您的问题,您需要使用与文本相同的值设置ID。将fetch.php的foreach更改为以下内容:

foreach ($list as $key => $value) {
    $data[] = array('id' => $value['tag'], 'text' => $value['tag']);                
} 

<强>更新 您还需要更新变量lastResults以避免重复使用相同文本的标记。绑定select2时,您需要将results的{​​{1}}属性更改为此(基于this answer

ajax

请注意ajax: { multiple: true, url: "fetch.php", dataType: "json", type: "POST", data: function(term) { return {q: term}; }, results: function(data) { lastResults = data.results; return {results: data}; }, }, 。如果没有这个,lastResults = data.results;变量始终为空,并且当执行lastResults函数时,它将始终返回一个新标记。

答案 1 :(得分:0)

最后它现在正在运作。我要感谢@alex&amp; @milz的支持。 这是完整的n最终代码。现在没有创建重复的标签。但是,我正在努力在数据库中添加标签。

php / html文件

<div class="form-group">
   <label class="col-sm-4 control-label">Product Name</label>
   <div class="col-sm-6">
      <input type="hidden" id="tags" style="width: 300px"/>
   </div>
</div>

<script type="text/javascript">
var lastResults = [];

$("#tags").select2({
    multiple: true,
    tags: true,
    placeholder: "Please enter tags",
    tokenSeparators: [',', ' '],//[","],
    initSelection : function (element, callback) {
        var data = [];
        $(element.val().split(",")).each(function () {
            data.push({id: this, text: this});
        });
        callback(data);
    },
    ajax: {
        multiple: true,
        url: "fetch.php",
        dataType: 'json',
      //  type: "POST",
       data: function(term,page) {
                        return {
                            term: term
                           };
                    },
                    results: function(data,page) {
                         lastResults = data;                       
                          return {results: data};

                    }, 
    },
    maximumSelectionSize: 3,
    minimumInputLength: 3,
createSearchChoice: function(term) {
    console.log($(this).attr('data'));
    var text = term + (lastResults.some(function(r) {

     console.log(r.text);
      console.log(term);
      return r.text == term
    }) ? "" : " (new)");

    return {
      id: term,
      text: text
    };
  },
});

$('#tags').on("change", function(e){
    if (e.added) {
        if (/ \(new\)$/.test(e.added.text)) {

           var response = confirm("Do you want to add the new tag "+e.added.id+"?");
           if (response == true) {
              alert("Will now send new tag to server: " + e.added.id);
              /*
               $.ajax({
                   type: "POST",
                   url: '/someurl&action=addTag',
                   data: {id: e.added.id, action: add},    
                   error: function () {
                      alert("error");
                   }
                });
               */
           } else {
                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);
                }
           }
        }
    }
});
</script>

这是从数据库获取数据的php文件。 的 fetch.php

<?php 
// connect to database 
require('db.php');

// strip tags may not be the best method for your project to apply extra layer of security but fits needs for this tutorial 
//if(isset($_GET)){
$search = strip_tags(trim($_GET['term'])); 

// Do Prepared Query 
$query = $mysqli->prepare("SELECT tid,tag FROM tag WHERE tag LIKE :search LIMIT 4");

// Add a wildcard search to the search variable
$query->execute(array(':search'=>"%".$search."%"));

$list = $query->fetchall(PDO::FETCH_ASSOC);

if(count($list) > 0){
   foreach ($list as $key => $value) {
    $data[] = array('id' => $value['tag'], 'text' => $value['tag']);            
   } 
} else {
   $data[] = array('id' => 'No Products Found', 'text' => 'No Products Found');
}

echo json_encode($data);

?>

花了很多时间。差不多3天。我希望它会挽救一些人的努力。

答案 2 :(得分:0)

应用下面的 select2.min.js (v4.0.6-rc.1) 代码片段中的更改

第 1 节

c.on("results:select", function() {
                    var a = e.getHighlightedResults();
                    if (0 !== a.length) {
                        var c = b.GetData(a[0], "data");
                        "true" == a.attr("aria-selected") ? e.trigger("close", {}) : e.trigger("select", {

                        //custom select2 tagging
                        if(a.attr("aria-selected")){
                            c.id = c.id + 1;
                        }
                        e.trigger("select", {
                            data: c
                        })

                        //"true" == a.attr("aria-selected") ? e.trigger("close", {}) : e.trigger("select", {
                        // e.trigger("select", {
                        //     data: c
                        // })

                    }
                })

第 2 节

this.on("query", function(b) {
                    a.isOpen() || a.trigger("open", {}), this.dataAdapter.query(b, function(c) {
                        //custom select2 tagging
                        let searchInput = $(".select2-search__field").val();
                        searchInput = {results: [{id: searchInput, text: searchInput}]};
                        a.trigger("results:all", {
                            data: c,
                            data: searchInput,
                            query: b
                        })
                    })
                })