简体   繁体   中英

Remove autocomplete selected item from the list in asp.net and Ajax

I am in the biggest problem **PLEASE DONT REPORT MY QUESTION DUPLICATE BECAUSE I DID NOT GET ANSWER FOR ASP.NET IN GOOGLE.

I am using jquery Autocomplete textbox in asp.net using web service. my code

 $('input.txtE').autocomplete({ source: function (request, response) { $.ajax({ url: "WebServices.asmx/GetNames", type: "POST", dataType: "json", contentType: "application/json; charset=utf-8", data: "{ 'txtInput' : '" + request.term + "','userName':'" + userName + "'}", dataFilter: function (data) { return data; }, success: function (data) { mydata = data.d; response($.map(data.d, function (item) { return { label: item.split('/')[0], val: item.split('/')[1] } })) }, error: function (result) { alert("Error"); } }); }, multiselect: false, minLength: 1, delay: 0, select: function (e, ui) { $(hfId).val(ui.item.val); } }); 

<input type="hidden" id="hfId"/>

And my API return data in array format

 ["Abhishek/128", "Abyss/71", "athansiah/53", "blvsian/138", "DesmondH/91", "destined2hold/62", "dnbdesigns/94", "Dvus_lotus/85", "gserranof/47", "Illusions/89", "isaacwu111/111", "js/39"]

What I need if a user selected remove him from the autocomplete list so we can't select him again.

Please help me to short out it.

尝试使用jQuery从数组中删除选定的值。

x = jQuery.grep(x, function(val) {return val != Item;});

Preparation

In first, you need to store setected values. It is possible by using a global variable, hidden input control or arbitrary data associated with your control. In the following example I create an array that is associated with autocomplete control and then store selected values to the array:

$('#my-control').autocomplete({
  create: function( e, ui ) {
    // initialize array
    $(this).data('selected', []);
  },
  select: function( e, ui ) {
    // store unique selected values
    var selected = $(this).data('selected');
    if(!~selected.indexOf(ui.item.value)) {
      selected.push(ui.item.value);
    }
  },

  // another options here

});

Now it is possible to consider the selected values for list filtering.

Server-side solution

The best way is to filter the list on API server side, because it reduces transferred data amount. Just send the stored values through an AJAX request, using data option:

var $control = $('#my-control');
$control.autocomplete({
  source: function (request, response) {
    $.ajax({

      // some AJAX options

      data: {
        term: request.term,
        selected: $control.data('selected') // send stored values
      }
    });
  },

  // some autocomplete options here

});

Then you have to implement server-side filtration in accordance to selected query string parameter. For example

public class AutocompleteSourceController : ApiController
{
    [HttpGet]
    public JsonResult<IEnumerable<MyClass>> GetItems(
        [FromUri]string term, 
        [FromUri]int[] selected)
    {
        // Load data
        // Fliter by term substring
        // Exclude selected items
        // Return the result
    }
}

Client-side solution

Another way is to filter responded list on client side, using success AJAX callback. In my example I will use fake online REST API server . The server ignores the term field of query string, so I also have to implement it on client-side.

 $control = $('#my-input'); $control.autocomplete({ create: function(e, ui) { $(this).data('selected', []); }, source: function(request, response) { $.ajax({ url: "https://jsonplaceholder.typicode.com/users", type: "GET", dataType: "json", contentType: "application/json; charset=utf-8", success: function(data) { var items = data // filter by term .filter(function(user) { return ~user.name.toLowerCase().indexOf(request.term.toLowerCase()); }) // exclude stored selected values .filter(function(user) { return !~$control.data('selected').indexOf(user.id); }) // cast to an objects with label and value properties .map(function(user) { return { label: user.name, value: user.id } }); response(items); }, error: function(result) { alert("Error"); } }); }, multiselect: false, minLength: 1, delay: 0, select: function(e, ui) { e.preventDefault(); $ctrl = $(this); var selected = $control.data('selected'); if (!~selected.indexOf(ui.item.value)) { // store selected value selected.push(ui.item.value); // set label instead of value $ctrl.val(ui.item.label); } }, }); 
 <link rel="stylesheet" type="text/css" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js" integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU=" crossorigin="anonymous"></script> <input id="my-input" type="text"> 

Type L to the input control. The first item will be Leanne Graham , select it. Then clean the input field and type L again, there will no Leanne Graham in the dropdown menu. Select Ervin Howell , then clean the input field and type L again. There will be neither Leanne Graham nor Ervin Howell in the dropdown menu.

If you want to consider only current selected value, you could store only latest value instead of an array and modify the success callback and the select event handler.

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