在 jquery 多个自动完成 ajax 中删除已选择的值

Remove already selected value in jquery multiple autocomplete ajax

如何删除 jQuery 多个自动完成列表中已选择的值?

例如,如果我选择了 word A,下次输入时它就不会出现在列表中。此外,如果有人试图使用退格键删除元素,该元素应该重新出现在自动完成列表中。

$(function() {
  function split(val) {
    return val.split(/,\s*/);
  }

  function extractLast(term) {
    return split(term).pop();
  }

  $("#birds").on("keydown", function(event) {
    if (event.keyCode === $.ui.keyCode.TAB &&
      $(this).autocomplete("instance").menu.active) {
      event.preventDefault();
    }
  }).autocomplete({
    source: function(request, response) {
      $.getJSON("search.php", {
        term: extractLast(request.term)
      }, response);
    },
    select: function(event, ui) {
      var terms = split(this.value);
      terms.pop();
      terms.push(ui.item.value);
      terms.push("");
      this.value = terms.join(", ");
      return false;
    }
  });
});

如果你存储 id 和文本可能会更好为什么不呢,每当你发出 ajax 请求传递这些并在服务器端处理它们时。

some_array = array();
$('[your-list]').keyup(function(e) {
  var text = $(this).text();
  // key backspace is released
  if(e.keyCode == 8)
    some_array.push(text);
});

好的,我制作了这个片段,它应该可以满足您的需要。我已经从 jquery ui 自动完成站点 https://jqueryui.com/autocomplete/ 获取了演示数据,因此您必须替换数据库中的数据

 $( function() {
    // Demo data -- store the data according to your need from database.
    let availableTags = [
      "ActionScript",
      "AppleScript",
      "Asp",
      "BASIC",
      "C",
      "C++",
      "Clojure",
      "COBOL",
      "ColdFusion",
      "Erlang",
      "Fortran",
      "Groovy",
      "Haskell",
      "Java",
      "JavaScript",
      "Lisp",
      "Perl",
      "PHP",
      "Python",
      "Ruby",
      "Scala",
      "Scheme"
    ];
    
    // define a new variable so that the original variable is not affected.
    let new_availableTags = []; 
    
    // define a variable to store all the selected values.
    let selectedVal       = []; 

    function split( val ) {
      return val.split( /,\s*/ );
    }
    function extractLast( term ) {
      return split( term ).pop();
    }

    // prevent the user from going behind via cursor //cursor always on last
    $( "#tags" ).on('click', (event) => {
      event.currentTarget.setSelectionRange(-1, -1);
    });

    $( "#tags" )
      // don't navigate away from the field on tab when selecting an item
      .on( "keydown", function( event ) {
        
        // prevent from giving space(32), delete(46), going back(37) and forward(39), delete a whole word(Ctrl + Backspace(8))
        if(event.keyCode == 32 || event.keyCode == 46 || event.keyCode == 37 || event.keyCode == 39 || (event.ctrlKey && event.keyCode == 8)){
         
          event.preventDefault();
        
        }else if(event.keyCode == 8){ // on pressing backspace
          
          let prev_val = event.currentTarget.value; //get the current input value
          let last_char = prev_val.charAt(prev_val.length-1); //get the last character of value
          
          if(last_char == ','){
            selectedVal.pop();  //delete last element only if last character is a comma(,)
          }
        }
        
        if (event.keyCode === $.ui.keyCode.TAB && $(this).autocomplete("instance").menu.active) {
            event.preventDefault();
        }
        //console.log(selectedVal);
        new_availableTags = availableTags;  //assign the value to the new variable
        
        selectedVal.forEach((selected) => {
            // only keep the values which are not selected
            new_availableTags = new_availableTags.filter(item => item != selected);
          });
      })
      .autocomplete({
        minLength: 0,
        source: function( request, response ) {
          // delegate back to autocomplete, but extract the last term
          response( $.ui.autocomplete.filter(
          new_availableTags, extractLast( request.term ) ) );
        },
        focus: function() {
          // prevent value inserted on focus
          return false;
        },
        select: function( event, ui ) {
          
          selectedVal.push(ui.item.value);  // insert the selected value in selectedVal
          console.log(`selectedVal: ${selectedVal}`);
          var terms = split( this.value );
          // remove the current input
          terms.pop();
          // add the selected item
          terms.push( ui.item.value );
          
          // add placeholder to get the comma-and-space at the end
          terms.push( "" );
          this.value = terms.join( ", " );
          return false;
        }
      });
  } );
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Autocomplete - Multiple values</title>
  <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="https://jqueryui.com/resources/demos/style.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

</head>
<body>
 
<div class="ui-widget">
  <label for="tags">Tag programming languages: </label>
  <input id="tags" size="50">
</div>
</body>
</html>

也许这有点像你想要的:

$( function() {
    // Demo data -- store the data according to your need from database.
    let availableTags = [
      "ActionScript",
      "AppleScript",
      "Asp",
      "BASIC",
      "C",
      "C++",
      "Clojure",
      "COBOL",
      "ColdFusion",
      "Erlang",
      "Fortran",
      "Groovy",
      "Haskell",
      "Java",
      "JavaScript",
      "Lisp",
      "Perl",
      "PHP",
      "Python",
      "Ruby",
      "Scala",
      "Scheme"
    ];

  function getTermRemainder(str, p) {
let part1 = str.substring(0,p).split(',');
let part2 = str.substring(p).split(',');
let term = (part1.pop() + part2.shift()).trim();
part1 = part1.join(',').trim();
part2 = part2.join(',').trim();
let remainder = part1.length ? (
    part2.length ? part1 + ', ' + part2 : part1
  ) : (
    part2.length ? part2 : ''
  );
return {
    term: term,
    remainder: remainder
};
  }

    
  $("#birds")
  .autocomplete({
focus: function(e, ui) {
  return false;
},
source: function(request, response) {
    let start = this.element.get(0).selectionStart;
    let { term, remainder } = getTermRemainder(request.term, start);
    term = term.toLowerCase();
    let terms = remainder.split(',');
    let hash = {};
    for(let i = 0, l = terms.length; i < l; i++)
        hash[terms[i].trim()] = true;
    let matched = availableTags
    .filter(function(item) {
        return(
            item.toLowerCase().indexOf(term) !== -1 &&
            !hash[item]
        );
    });
    response(matched);
},
select: function(event, ui) {
  let selected = ui.item.value;
  let val = this.value;
  let pos = this.selectionStart;
  let start = pos;
  while(--start > 0) if(val.charAt(start) === ',') break;
  let end = pos-1;
  let l = val.length;
  while(++end < l) if(val.charAt(end) === ',') break;
  let result = '';
  if(start > 0) result += val.slice(0,start) + ', ';
  result += selected;
  if(end < l) result += val.slice(end);
  else result += ', ';
  this.value = result;
  return false;
}
  });
});
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Autocomplete - Multiple values</title>
  <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="https://jqueryui.com/resources/demos/style.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

</head>
<body>
 
<div class="ui-widget">
  <label for="birds">Tag programming languages: </label>
  <input id="birds" size="50">
</div>
</body>
</html>