Remove selected item from array in jQuery autocomplete

I have this array,

var metrics = [ { value: "1", label: "Sold Listings", desc: "sold_listings" }, { value: "10", label: "New Pendings", desc: "new_pendings" }, { value: "4", label: "All Pendings", desc: "all_pendings" }, { value: "2", label: "New Listings", desc: "new_listings" }, { value: "3", label: "Active Listings", desc: "active_listings" } ]; 

What I wanted to do was select the Selected element, for example, I will select Active Listings, this element should be removed from the array. So when autocomplete is displayed again, it will not display the selected item.

 //My Idea of removing the item $.each(metrics,function(i,val){ if(val.value == ui.item.value){ delete metrics[i]; } }); 
+4
source share
2 answers

The problem is that you did not update the autocomplete source.
For this you should use the following line.

$('.yourAutocomplete').autocomplete('option', 'source', yourArray);

So, with the select autocomplete event:

Assuming #autocomplete is your input .

 select: function(e, ui) { metrics = jQuery.grep(metrics, function(element) { return element.value != ui.item.value; }); $('#autocomplete').autocomplete('option', 'source', metrics) return false; } 

demo

Link:

+5
source

From this post you can do something like:

 var y = [1, 2, 3] var removeItem = 2; y = jQuery.grep(y, function(value) { return value != removeItem; }); 

EDIT:

As an example, you can:

 var removeItem = "1"; metrics = $.grep(metrics, function(val) { if (val.value != removeItem) { return val; } }); 

This will delete the first element of the array with a value of "1".

+2
source

Source: https://habr.com/ru/post/1438081/


All Articles