简体   繁体   中英

Jquery or javascript - Remove item from Array

I have a select list, when an item is clicked, the item is added to a div. The list is made up of users from a PHP call.

I now want to remove the item from the list when it is clicked.

How can I remove an item from the list without breaking my code?

Here is the javascript:

$(function() {
  var myUsers = new Array();
  $("#keyword").autocomplete({
    source: function(request, response) {
      $.ajax({
        url: "dist_user_search.php",
        data: {
          term: $('#keyword').val()
        },
        dataType: "json",
        success: function(data) {
          console.log('success');
          var res = [];
          for (var item of data) {
            if (item['myResult']) {
              res.push(item['myResult']);
            }
          }
          response(res);
        }
      });
    },
    minLength: 2,
    select: function(event, ui) {
      if (myUsers.indexOf(ui.item.value) < 0) {
        myUsers.push(ui.item.value);
        var str = "";
        myUsers.forEach(function(myUser) {
          str = '<li>' + myUser + '</li>' // build the list
        });
        $('#log').append('<div>' + str + '</div>'); // append the list
        $('#keyword').val('');
        return false;
      } else {
        $('#keyword').val('');
        return false;
      }
    }
  });
});

html:

<div class="ui-widget">
  <label for="keyword">Users: </label>
  <input id="keyword">
</div>


<div class="ui-widget" style="margin-top:2em; font-family:Arial">
  Result:
  <div id="log" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></div>
</div>

You can add click-handlers to the li-items every time you rebuild the list.

 var myUsers = new Array(); $("#keyword").autocomplete({ source: function (request, response) { var res = []; for (var i = 0; i < 3; i++) { res.push("Item " + i); } response(res); }, minLength: 0, // Just for testing, set this to 0 select: function (event, ui) { if (myUsers.indexOf(ui.item.value) < 0) { myUsers.push(ui.item.value); var str = ""; // Notice how I changed 'str =' to 'str +=' myUsers.forEach(function(myUser) { str += '<li>' + myUser + '</li>' }); // Changed 'append' to 'html' to always show an up-to-date list $('#log').html('<div>' + str + '</div>'); $("#log li").off("click").click(function () { var removed = $(this).remove().text(); $("#removed").append(removed + ", "); // Added this, to clear the user from the 'myUsers' array as well. myUsers.splice(myUsers.indexOf(removed)); }); } $('#keyword').val(''); return false; } }); 
 .ui-helper-hidden-accessible { display: none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script> <div class="ui-widget"> <label for="keyword">Users: </label> <input id="keyword"> </div> <div style="margin-top: 100px;"><ul id="log"></ul></div> <div id="removed">Removed: </div> 

Edit: Changed to code to look more like your scenario, I marked with comments what I think will fix an unrelated bug and the reason why you aren't seeing any users the second time.

i use this code and works fine:

     //get the index of item
     var index = myArray.indexOf("itemToRemove");
     //if exists
     if (index > -1) {
       //remove
        myArray.splice(index, 1);
     }  

In the end, this is what I did. I make use of an array for convenience later when I need to save the items.

When I remove I remove from the div and the array at the same time.

 <script>
  $( function() {

  var myUsers = new Array();



    $( "#keyword" ).autocomplete({
   source: function( request, response ) {


        $.ajax( {
          url: "dist_user_search.php",
          data: {term : $('#keyword').val()},
          dataType: "json",
          success: function( data ) {
          console.log('success');
          var res = [];
          for (var item of data){
          if (item['myResult']){
            res.push(item['myResult']);
            }
          }

          response( res );
          }
        } );
      },
      minLength: 2,
      select: function( event, ui ) {


      if(myUsers.indexOf(ui.item.value) < 0){
        myUsers.push(ui.item.value);


        var str = "";
        myUsers.forEach(function(myUser){
        str = '<li>' + myUser + ' X </li>' // build the list
        });

        $('#log').append('<div>' + str + '</div>'); // append the list


         $("#log li").off("click").click(function () {
    var $this = $(this);
    $("#removed").append($this.text() + ", ");
    $this.remove();

    //remove from array..
    myUsers.splice($.inArray($this, myUsers),1);

    //debug show array.
    //alert(myUsers);

  });


       $('#keyword').val(''); return false;

       } 


      }
    } );


    //console.log(myUsers);
  } );


  </script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM