jQuery select2: duplicate tag getting recreated

前端 未结 2 450
刺人心
刺人心 2021-01-25 03:27

I asked a question earlier today (jquery select2: error in getting data from php-mysql). However, I am trying to fix it and doing that now I am getting bit strange issue. I am n

相关标签:
2条回答
  • 2021-01-25 04:08

    Tags need an id and a text. The issue you're facing is that your text doesn't match the id.

    So, even if you write the same text, Select2 thinks the new text is a new option because the id don't match.

    To solve your issue, you need to set the id with the same value as the text. Change the foreach of your fetch.php to the following:

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

    Update: You also need to update the variable lastResults to avoid the duplication of tags with the same text. When you bind select2, you need to change the results property of ajax to this (based on this answer:

    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};
        }, 
    },
    

    Note the lastResults = data.results;. Without this, the lastResults variable is always empty and, when the createSearchChoice function is executed, it will always return a new tag.

    0 讨论(0)
  • 2021-01-25 04:10

    Finally it is working now. I would like to thanks @alex & @milz for their support. Here is the full n final code. Now duplicate tags are not creating. However, i am working to add tag in database.

    php/html file

    <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>
    

    Here is the php file to get the data from database. 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);
    
    ?>
    

    It took lots of time. Almost 3 days. I hope it will save someone efforts.

    0 讨论(0)
提交回复
热议问题