jQuery select2: duplicate tag getting recreated

前端 未结 2 451
刺人心
刺人心 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.

提交回复
热议问题