如何在jquery自动完成中添加新项目选项?

时间:2014-07-24 09:24:38

标签: javascript jquery jquery-ui twitter-bootstrap autocomplete

我已实施自动完成功能。我实施了bootstrap Modal。我想要做的就是在自动完成响应中添加一个新选项,即最后Add new Item

那么如何实现这一点。我的自动填充代码如下:

$(document).ready(function () {
            var makesCache = {}, modelsCache = {}, makesXhr, modelsXhr;

            $('#<%= txtName.ClientID%>').autocomplete({
                source: function (request, response) {
                    var term = request.term;
                    if (term in makesCache) {
                        response(makesCache[term]);
                        return;
                    }
                    if (makesXhr != null) {
                        makesXhr.abort();
                    }
                    makesXhr = $.getJSON('AutoComplete.svc/GetProjects', request, function (data, status, xhr) {
                        makesCache[term] = data.d;
                        if (xhr == makesXhr) {
                            response(data.d);
                            makesXhr = null;
                        }
                    });
                }
            });
        });

模式的html,我希望通过autocomplete中的选项可见:

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">

所以如何实现这个!!

1 个答案:

答案 0 :(得分:3)

这可以通过在自动填充的“打开”事件中实施一些更改来完成。

API参考:http://api.jqueryui.com/autocomplete/#event-open

$(document).ready(function () {
        var makesCache = {}, modelsCache = {}, makesXhr, modelsXhr;

        $('#<%= txtName.ClientID%>').autocomplete({
            source: function (request, response) {
                var term = request.term;
                if (term in makesCache) {
                    response(makesCache[term]);
                    return;
                }
                if (makesXhr != null) {
                    makesXhr.abort();
                }
                makesXhr = $.getJSON('AutoComplete.svc/GetProjects', request, function (data, status, xhr) {
                    makesCache[term] = data.d;
                    if (xhr == makesXhr) {
                        response(data.d);
                        makesXhr = null;
                    }
                });
            },
            'open': function(e, ui) {
                    // Appends a div at the end, containing the link to open myModal
                    $('.ui-autocomplete').append("<div id='endtext'><a href='#' data-toggle='modal' data-target='#myModal'>Click here to display my modal</a></div>");
    }
        });
    });