I have a jQuery UI Autocomplete bound to an input element and a custom display of the items in the Autocomplete box. Each item has multiple lines and I want to separate the items clearly from each other, for example using a <hr /> element. The following works but it also renders a <hr /> element after the last item:
$(function () {
$("#Customer").autocomplete({
source: "/SomePath/SearchCustomers?term=ABC",
select: function (event, ui) {
$("#CustomerId").val(ui.item.customerId);
return false;
}
})
.data("autocomplete")._renderItem = function (ul, item) {
var renderedItem = $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + item.customerId + ", " + item.name + "<br />"
+ item.addressLine1 + "<br />"
+ item.countryCode + ", " + item.city + "</a>");
// if (IsNotTheLastItem(item)) <-- Is something like this possible?
renderedItem = renderedItem.append("<hr />");
renderedItem = renderedItem.appendTo(ul);
return renderedItem;
};
});
(The code is derived from the example here: http://jqueryui.com/demos/autocomplete/#custom-data (click on “View Source”).)
Is it possible to determine if the item I am going to render is the last item (as indicated in the comment line above)? Or is there some alternative to add a separator between items, but not after the last item?
Since you’re clearly using the
<hr>element only for a visual purpose, I think you could easily solve this problem with CSS only: instead of generating a<hr>element inside every<li>via javascript, just assign a border-top to every<li>except the first one withthe resulting effect will be a line under each list item except the last one and you will avoid to inject markup via javascript and – more important – to insert unnecessary logic to detect your last item