Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering autocomplete suggestions in a pre-defined html block using jquery

I have a predefined HTML code say,

<div id="wrapper">
   <div class="element"></div>
   <div class="element"></div>
   <div class="element"></div>
</div>

and I have a input box. I have a remote source which can return me the results in jsonp format. I want to utilize jquery's autocomplete feature, but instead of the results being shown in a dropdown newly created div, I want to populate them in my existing HTML shown above.

I tried searching a lot for it, but I don't seem to find a way to do that. I'm fairly new to jquery, so pardon me if I'm missing something too obvious.

like image 237
ZombieCoder Avatar asked Feb 23 '26 10:02

ZombieCoder


1 Answers

jQuery UI autocomplete has inbuilt functionality to customize the display of the results. This demo shows how it can be achieved which overrides the _renderItem method of the "autocomplete" data attribute inside the jQuery UI autocomplete code.

HTML

<label for="tags">Tags: </label><input id="tags" />
<div id="wrapper"></div>

JavaScript

$('#tags').autocomplete({
    source: availableTags,
    search: function(event, ui) {
       // clear the existing result set
       $('#wrapper').empty();
    },
})
.data('autocomplete')._renderItem = function(ul, item) {
    return $('<div class="element"></div>')
        .data('item.autocomplete', item)
        .append('<a href="#">' + item.label+ '</a>')
        .appendTo($('#wrapper'));
    };

CSS& (to hide the normal container)

.ui-autocomplete {
    display:none !important;
}

You can customize each item by changing the markup inside the .append() method in the .data('autocomplete') function and you may want to look at the other autocomplete Events if you want to manipulate the <div id="wrapper"> search results further, for example clearing the list if the <input> acquires focus.

like image 78
andyb Avatar answered Feb 25 '26 07:02

andyb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!