Reputation: 935
I am adding content to a list dynamically and I want to be able to prevent adding duplicates. So before content is added I am selecting all the list, make an array and check that the data I am adding is not already contained in the list. However I get a unexpected identifier in my code. This is my code:
$(".autocomp_centers").autocomplete({
var ids = new Array();
$("#sister-centers-list > li").each(function(index, value){
ids.push($(value).attr('class'));
console.log($(value).attr('class'));
});
serviceUrl:'/suggest_centers',
maxHeight:400,
width:252,
params: {country: $("#country").val() },
minChars:2,
onSelect: function(value, data){
if ($.inArray(data, ids) == -1){
alert("Sister center has already been added.");
}else{
$("#hidden-ids").append('<input type="hidden" name="center_ids[]" value="' + data +'" class="center-' + data + '"/>');
$('#sister-centers-list').append('<li class="center-' + data + '">' + value + ' <a href="#sister-center" class="remove-center-before-save" id="' + data + '">Remove</a></li>');
}
$("#sister-search").val("");
}
});
When the person starts typing and this method is called, I get the list values and store them in an array. When they select a value, I check if the value is already in the array. This is the line that causes the error: var ids = new Array();
Upvotes: 0
Views: 683
Reputation: 2214
The autocomplete command (http://api.jqueryui.com/autocomplete/) requires an object as a parameter -- you cannot write the code directly between the object properties.
Try something like this instead:
var ids = new Array();
$("#sister-centers-list > li").each(function(index, value){
ids.push($(value).attr('class'));
console.log($(value).attr('class'));
});
$(".autocomp_centers").autocomplete({
serviceUrl:'/suggest_centers',
maxHeight:400,
width:252,
params: {country: $("#country").val() },
minChars:2,
onSelect: function(value, data){
if ($.inArray(data, ids) == -1){
alert("Sister center has already been added.");
}else{
$("#hidden-ids").append('<input type="hidden" name="center_ids[]" value="' + data +'" class="center-' + data + '"/>');
$('#sister-centers-list').append('<li class="center-' + data + '">' + value + ' <a href="#sister-center" class="remove-center-before-save" id="' + data + '">Remove</a></li>');
}
$("#sister-search").val("");
}
});
Of course, depending on what your application does, you may have to make more changes. For example if you have multiple "autocomplete" things on the same page, you may want to use a separate array of IDs for each of them. Etc.
Upvotes: 1
Reputation: 943220
You've started an object literal when it looks like you intended to start a function.
{
var ids = new Array();
You probably want:
function () {
var ids = new Array();
Upvotes: 1