c01gat3
c01gat3

Reputation: 597

Append and persist additional element to jQuery ui-autocomplete

What I want to achieve is that when a user searches for a result, the last result is always the option to "add new".

I also want to persist that option even after no more results are available. So when the auto-complete has no more results, it still shows the "add new" option. The option should only disappear after the field loses focus.

So far I can display the option, but am unable to keep it there after the available results have been exhausted. I don't know how to approach this part?

Append one link to jquery ui autocomplete and Add additional link to jquery ui autocomplete list didn't help with the persisting part of the problem.

Here is a fiddle https://jsfiddle.net/c01gat3/ufa70bza/

Cheers.

$(function() {

    var addnew = '<li class="ui-menu-item" id="addnew" onClick="alert(\'add new customer\')">Add New Customer</li>';

    var availableTagsCustomerCode = [
    "ABCE001",
    "ABCD010",
    "BCDE100",
    "CDEF002",
    "DEFG020",
    "EFGH200",
    ];

    $( "#customer-code" ).autocomplete({
        source: availableTagsCustomerCode,

        'open': function(e, ui) {
                $(".ui-autocomplete").append(addnew);
            }
    });
});

Upvotes: 1

Views: 1768

Answers (1)

Mauricio Moraes
Mauricio Moraes

Reputation: 7373

Try adding a message to say that no results where found. As you already added a callback for the "open" event, it will come naturally. See the fiddle below.

$(function() {

var addnew = '<li class="ui-menu-item" id="addnew" onClick="alert(\'add new customer\')">Add New Customer</li>';

var availableTagsCustomerCode = [
"ABCE001",
"ABCD010",
"BCDE100",
"CDEF002",
"DEFG020",
"EFGH200"
];

$( "#customer-code" ).autocomplete({
    source: availableTagsCustomerCode,

    'open': function(e, ui) {
            $(".ui-autocomplete").append(addnew);
        },
    response: function(event, ui) {
        if (!ui.content.length) {
            var noResult = { value:"",label:"No results found" };
            ui.content.push(noResult);
        }
    }
});
});

https://jsfiddle.net/ufa70bza/2/

Upvotes: 3

Related Questions