I have this code which I have analysed in Firebug and it is really confusing me. When I call this code the line alert(selectedAmenities); shows the correct data but this line
source: "/Results/GetAmenities?selected=" + selectedAmenities,
always shows selectedAmenities as being an empty string. Why is this?
$(function () {
var selectedAmenities = "";
function amenitiesLog(message) {
if (!$('#amenitiesLog div:contains(' + message + ')').length) {
$("<div/>").text(message).appendTo("#amenitiesLog");
$("<br/>").text("").appendTo("#amenitiesLog");
$("#amenitiesLog").scrollTop(0);
selectedAmenities = document.getElementById("amenitiesLog").innerHTML;
alert(selectedAmenities);
}
}
$("#Amenities").autocomplete({
source: "/Results/GetAmenities?selected=" + selectedAmenities,
minLength: 3,
select: function (event, ui) {
if (ui.item != null) amenitiesLog(ui.item.value);
}
});
});
Then
getElementByIdworks perfectly fine.The problem
The line
is executed before you call
amenitiesLog(ui.item.value);and it is only executed once.At the moment you read
selectedAmenities, it is an empty string and changing the value later does not update"/Results/GetAmenities?selected=" + selectedAmenities.If I have
then
barstays'answer42', it does not change withfoo.barcontains a string and has no relation to the variablefoowhatsoever.The solution
Instead of using the URL as source, it seems you should use a callback. Have a look at the overview section in the documentation. Something like:
The difference is that now whenever the autocomplete is triggered, the function you assigned to
source:will be called and it re-evaluates"/Results/GetAmenities?selected=" + selectedAmenitiesevery time.