jQuery UI autocomplete- no results message

前端 未结 4 562
一个人的身影
一个人的身影 2020-12-02 01:59

I\'m trying to have a \"No Results\" message appear in the dropdown menu if there are no results. So for instance, if I type in \"ABCD\" into the text field, and there is n

4条回答
  •  鱼传尺愫
    2020-12-02 02:03

    My answer is almost identical to @neelmeg and @Trever, but I have added an extra check, so user won't be able to select the "no result" message:

    $(".my-textbox").autocomplete({
        minLength: 2,
        open: function () { $('.ui-autocomplete').css('z-index', 50); },
        source: function (request, response) {
            $.ajax({
                url: "/some-url",
                type: "POST",
                dataType: "json",
                data: { prefix: request.term, __RequestVerificationToken: token },
                success: function (data) {
                    if (!data.length) {
                        var result = [{ label: "no results", value: response.term }];
                        response(result);
                    }
                    else {
                        response($.map(data, function (item) {
                            return { label: item.someLabel, value: item.someValue };
                        }))
                    }
                }
            })
        },
        select: function (event, ui) {
            var label = ui.item.label;
                if (label === "no results") {
                // this prevents "no results" from being selected
                event.preventDefault();
            }
            else {
                /* do something with the selected result */
                var url = "some-url"
                window.location.href = url;
            }
        }
    });
    

提交回复
热议问题