jQuery ui带有Google Places的自动完成功能-向下箭头移动时强制选择并删除原始输入

5 javascript jquery jquery-ui autocomplete

我正在关注jQuery ui autocomplete,它从Google地方获取数据...

我遇到的问题是,一旦用户开始通过上下箭头浏览建议列表,原始输入也会出现在末尾。我想删除此原始输入,否则,如果用户点击输入,则保存表单而不强制选择...

// Autocomplete location with google places API
    $("#edit_profile .location").autocomplete({
        source: function(request, response) {
            $.ajax({
                url: "/words/lib/ajax.php",
                type: "GET",
                data: "autocomplete_location=1&term=" + request.term,
                cache: false,
                success: function(resp) {
                    try {
                        json = $.parseJSON(resp);
                    } catch (error) {
                        json = null;
                    }
                    //
                    if (json && json.status == "OK") {
                        //
                        response($.map(json.predictions, function(item) {
                            return {
                                label: item.description,
                                value: item.description
                            }
                        }));
                        //
                    }
                }
            });
        },
        minLength: 1,
        change: function (event, ui) {
            if (!ui.item){
                $(this).val("");
            }
        }
    });
Run Code Online (Sandbox Code Playgroud)

LeG*_*GEC 0

[Enter]您是否担心在自动完成菜单可见时禁用默认操作?

如果是这样,这里有一个解决方案:在您的输入中添加一些标志,如果设置了该标志,则防止 keydown 上的默认操作:

var $input = $('input[name="name"]');

$input.on('keydown', function(e) {
    if ( $(this).data('acShown') && e.which == 13 /*enter key*/){
        e.preventDefault();
    }
});
$input.autocomplete({
    source: function (request, response) {
        setTimeout(function () {
            $input.data('acShown', true); //set the flag when showing the menu
            response(data)
        }, 300);
    },
    close: function(){
        $input.data('acShown', false); //unset the flag on close
    }
});
Run Code Online (Sandbox Code Playgroud)

小提琴

在小提琴中:正如您所看到的,当显示菜单时,[Enter]当焦点位于输入上时点击不会触发表单提交 - 您将停留在当前页面。