Jquery Autcomplete, how can I always show renderMenu, regardless of whether there are original matches?

I want to add a helper to jQuery autocomplete as follows:

var thing = $("#thing").autocomplete({ minLength: 0, source: myarray }) // Override the Render Menu thing.data("autocomplete")._renderMenu= function(ul, items) { var self = this; $.each( items, function( index, item ) { self._renderItem( ul, item ); }); // Adder ul.append( "<a class='helper'>Add <b>\"" + this.term + "\"</b> as a new item</a>") } 

The problem is that HELPER only appears when autocompletion has at least 1 search matched by myarray. How can I make the menu always show when the user is focused?

thanks

+4
source share
2 answers

I think a little more monkey patches are fine:

 /* Override the _response function to always open the suggestions menu: */ thing.data("autocomplete")._response = function(content) { if (!this.options.disabled) { this._trigger("open"); content = this._normalize(content); this._suggest(content); } this.pending--; if (!this.pending) { this.element.removeClass("ui-autocomplete-loading"); } }; 

Example: http://jsfiddle.net/eJMuf/

This should work, but I will continue to look for a solution using the standard API.


Here's another solution that does not require the same open heart operation, but requires more code:

 var thing = $("#thing").autocomplete({ minLength: 0, /* Use a source function instead of the array */ source: function(request, response) { var result = myArray.slice(0); /* Filter the array normally... */ result = $.ui.autocomplete.filter(result, request.term); /* Add a placeholder result that we can process later */ result.push({ value: request.term, isPlaceholder: true }); response(result); } }).focus(function() { $(this).autocomplete("search", this.value); }); var renderItem = thing.data("autocomplete")._renderItem; /* Override the _renderItem function to display the placeholder item */ thing.data("autocomplete")._renderItem = function(ul, item) { if (item.isPlaceholder) { return $("<li>") .data("item.autocomplete", item) .append("<a class='helper'>Add <b>\"" + item.value + "\"</b> as a new item</a>") .appendTo(ul); } else { renderItem(ul, item); } }; 

Example: http://jsfiddle.net/FvCY6/

I would personally go with this decision as it is less invasive.

+1
source

A better approach would be to add an element in terms of the number of elements you get from the backend.
If in its json array add a json object with a label and a special value of -1. In this case, the array will always contain one object. :)

0
source

Source: https://habr.com/ru/post/1403788/


All Articles