Question

I have jQuery code, which looks this way:

var FoundBanks = [];
 function search() {
  $.ajax({ url: "/bankir/banks_search/",
   data: { term: $("#search").val()},
   dataType: 'json',
   type: "POST",
   success: function(data){
      FoundBanks = [];
      for (var i in data) {
        if (typeof(data[i]) == "object") {
          FoundBanks.push(data[i]);
        }
      }
        $("#search").autocomplete({
          source: FoundBanks,
          minLength: 0,
          focus: function (event, ui) {
            $("#search").val(ui.item.name);
            return false;
          },
          select: function (event, ui) {
            window.location = "/bank/"+ui.item.id;
            return false;
          }
        })
        .data("ui-autocomplete")._renderItem = function (ul, item) {
          console.log("renderitem");
          return $("<li>")
            .append("<a>" + item.name + "</a>")
            .appendTo(ul);
        };
   }
 });
}

It makes query to MVC-based backend, get result in json (valid results, I checked), form an array.

For example, formed array looks like below:

[{id: "1", name:"abc"}, {id:"2", name: "bac"}, {id: "3", name: "cab"}]

If I type "a" - I don't see anything, but when I delete "a" - I see all three. So it's look like the jQuery doesn't know that it should look for a value in object.name.

Was it helpful?

Solution

You don't need to call function for it:

just have an input element:

<input type="text" id="search">

Try this:

$(function(){
    $("#search").autocomplete({
        source: function(request, response) {
            $.ajax({
                url: "/bankir/banks_search/",
                type: "POST",
                dataType: "jsonp",
                data: {
                    term: $("#search").val()
                },
                success: function(data) {
                    response($.map(data, function(item) {
                        return {
                            label: item.name,
                            value: item.id
                        };
                    }));
                }
            });
        },
        minLength: 0,
        focus: function(event, ui) {
            $("#search").val(ui.item.label);
        },
        select: function(event, ui) {
            window.location = "/bank/" + ui.item.value;
        }
    });
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top