Sachin Kainth
Sachin Kainth

Reputation: 46750

GetElementById not working in JQuery autocomplete call

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);
        }
    });
});

Upvotes: 0

Views: 903

Answers (1)

Felix Kling
Felix Kling

Reputation: 816422

When I call this code the line alert(selectedAmenities); shows the correct data

Then getElementById works perfectly fine.


The problem

The line

source: "/Results/GetAmenities?selected=" + selectedAmenities 

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

var foo = '42'; 
var bar = 'answer' + foo; 
foo = '21';

then bar stays 'answer42', it does not change with foo. bar contains a string and has no relation to the variable foo whatsoever.


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:

$("#Amenities").autocomplete({
    source: function(request, callback) {
         var url = "/Results/GetAmenities?selected=" + selectedAmenities + '&term=' + request.term;
         $.getJSON(url, callback);
    },
    minLength: 3,
    select: function (event, ui) {
        if (ui.item != null) amenitiesLog(ui.item.value);
    }
});

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=" + selectedAmenities every time.

Upvotes: 1

Related Questions