Faror Faror - 1 year ago 30
jQuery Question

$.map() is firing multiple times inside of an .autocomplete() success

I'm using the "autocomplete" function from jQuery UI to search for users in a database. The script is working and the program is finding everything I'm looking for. But when the autocomplete menu appears below the searching field, all the results appears multiple times. After looking for the problem I could locate the problematic function. It is

map()
. Maybe someone can help me out with this. Thanks You!

The function:

<!-- Dynamische Suche -->
$('#suchfeld').autocomplete({
    source : function (request, response) {
$.ajax({
type: "POST",
url: "post.php",
data: {
name:'Suchfeldvorschlaege',
value:request.term
},
success: function(json) {
var data = $.parseJSON(json);
var availableTagsLabeled = new Array();
response($.map(data, function () {
if(!data["0_SuchfeldName"]) {
availableTagsLabeled[0] = {label:"Keine Einträge"};
} else {
for(i = 0; i <= data.SuchfeldAnzahl; i++) {
availableTagsLabeled[i] = {label: data[i +"_SuchfeldName"], value: data[i +"_SuchfeldID"]};
}
}
return availableTagsLabeled;
}));
}
})
},
minLength : 3,
    select : function(event, ui) {
     $('#suchfeld').html(ui.item.label);
     $('#suchfeld').attr("data-KundenID", ui.item.value);
        return false; },
    focus : function(event, ui) {
     $(this).val(ui.item.label);
$('#suchfeld').attr("data-KundenID", ui.item.value);
    }
});`


(All my functions are inside off a
$(document).ready(function(){});
)

Answer Source

$.map() returns an array of all the values returned by the callback function. Your callback function is returning the entire availableTagsLabeled array, so $.map() is returning a 2-dimensional array. You should just return one element at a time.

But it doesn't look like you should be mapping over the JSON object at all. You just need the for loop to collect all the elements.

And your test for whether there are any elements to return should be done outside the loop.

success: function(json) {
    var var data = $.parseJSON(json);
    var availableTagsLabeled;
    if(!data["0_SuchfeldName"]) {
        availableTagsLabeled = [{label:"Keine Einträge"}];
    } else {
        availableTagsLabeled = [];
        for(i = 0; i <= data.SuchfeldAnzahl; i++) {
            availableTagsLabeled[i] = {label: data[i +"_SuchfeldName"], value: data[i +"_SuchfeldID"]};
        }
    }
    response(availableTagsLabeled);
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download