6

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 is to the Selected item, for example I will select Active Listings, this item should be deleted from the array. So that when the autocomplete renders again, it won't show the selected item.

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

2 Answers 2

6

The problem is that you didn't update the source of autocomplete.
To do it you have to use the following line.

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

So, on autocomplete select event:

Assuming that #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

Reference:

Sign up to request clarification or add additional context in comments.

3 Comments

how about if you add back the selected item into the array, when the remove button is clicked?
@Jetoox Remove one and add other ?
no. example if i click the removed button on one of the added items, how do i push it back into the array?
2

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:

For your example, you could do:

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

This will remove the first array item with value "1" property.

1 Comment

what if the array format is the same as I posted? Would that still be applicable with what you have answered?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.